# AI Fitness & Nutrition Coach - Complete Documentation > aifitapp is a subscription-based, AI-powered fitness and nutrition platform that generates personalized training programs and dietary plans using evidence-based principles. Users interact with an intelligent chatbot to receive customized workout regimes, meal recommendations, exercise and food alternatives, and educational guidance—all governed by strict safety and scientific protocols. This document contains the full documentation for all services in the AI Fitness & Nutrition Coach project. It is designed for comprehensive reference by both humans and AI agents. --- ## Table of Contents ### Getting Started - [Introduction](#intro) ### Frontend Prompts - [Project Introduction & Setup](#frontend-prompts-frontend-prompt-1-projectintroduction) - [Authentication Management](#frontend-prompts-frontend-prompt-2-authmanagement) - [Verification Management](#frontend-prompts-frontend-prompt-3-verification) - [Profile Management](#frontend-prompts-frontend-prompt-4-profile) - [User Management](#frontend-prompts-frontend-prompt-5-usermanagement) - [MCP BFF Integration](#frontend-prompts-frontend-prompt-6-mcpbffintegration) - [AiCoach Service](#frontend-prompts-frontend-prompt-7-aicoachservice) - [AiCoach Service AdditionalQuota Payment Flow](#frontend-prompts-frontend-prompt-8-additionalquota-payment-flow) - [Subscription Service](#frontend-prompts-frontend-prompt-9-subscriptionservice) - [Subscription Service Subscription Payment Flow](#frontend-prompts-frontend-prompt-10-subscription-payment-flow) - [AgentHub Service](#frontend-prompts-frontend-prompt-11-agenthubservice) ### Auth Service - [Service Design](#auth-service-service-design) - [REST API Guide](#auth-service-rest-api-guide) - [Event Guide](#auth-service-event-guide) - **Data Objects** - [user Design](#auth-service-user-design) - [userAvatarsFile Design](#auth-service-useravatarsfile-design) - **Business APIs** - [getUser API](#auth-service-business-api-getuser-api-design) - [updateUser API](#auth-service-business-api-updateuser-api-design) - [updateProfile API](#auth-service-business-api-updateprofile-api-design) - [createUser API](#auth-service-business-api-createuser-api-design) - [deleteUser API](#auth-service-business-api-deleteuser-api-design) - [archiveProfile API](#auth-service-business-api-archiveprofile-api-design) - [listUsers API](#auth-service-business-api-listusers-api-design) - [searchUsers API](#auth-service-business-api-searchusers-api-design) - [updateUserRole API](#auth-service-business-api-updateuserrole-api-design) - [updateUserPassword API](#auth-service-business-api-updateuserpassword-api-design) - [updateUserPasswordByAdmin API](#auth-service-business-api-updateuserpasswordbyadmin-api-design) - [getBriefUser API](#auth-service-business-api-getbriefuser-api-design) - [streamTest API](#auth-service-business-api-streamtest-api-design) - [registerUser API](#auth-service-business-api-registeruser-api-design) - [getUserAvatarsFile API](#auth-service-business-api-getuseravatarsfile-api-design) - [listUserAvatarsFiles API](#auth-service-business-api-listuseravatarsfiles-api-design) - [deleteUserAvatarsFile API](#auth-service-business-api-deleteuseravatarsfile-api-design) - **Database Buckets** - [userAvatars Bucket](#auth-service-db-buckets-useravatars-bucket-design) ### AiCoach Service - [Service Design](#aicoach-service-service-design) - [REST API Guide](#aicoach-service-rest-api-guide) - [Event Guide](#aicoach-service-event-guide) - **Data Objects** - [chatMessage Design](#aicoach-service-chatmessage-design) - [coachConversation Design](#aicoach-service-coachconversation-design) - [mealPlan Design](#aicoach-service-mealplan-design) - [moderationRecord Design](#aicoach-service-moderationrecord-design) - [planMeal Design](#aicoach-service-planmeal-design) - [programExercise Design](#aicoach-service-programexercise-design) - [quotaConfig Design](#aicoach-service-quotaconfig-design) - [trainingProgram Design](#aicoach-service-trainingprogram-design) - [userQuota Design](#aicoach-service-userquota-design) - [weightLog Design](#aicoach-service-weightlog-design) - [banAppeals Design](#aicoach-service-banappeals-design) - [additionalQuota Design](#aicoach-service-additionalquota-design) - [sys_additionalQuotaPayment Design](#aicoach-service-sys-additionalquotapayment-design) - [sys_paymentCustomer Design](#aicoach-service-sys-paymentcustomer-design) - [sys_paymentMethod Design](#aicoach-service-sys-paymentmethod-design) - **Business APIs** - [createChatMessage API](#aicoach-service-business-api-createchatmessage-api-design) - [createCoachConversation API](#aicoach-service-business-api-createcoachconversation-api-design) - [createQuotaConfig API](#aicoach-service-business-api-createquotaconfig-api-design) - [createWeightLog API](#aicoach-service-business-api-createweightlog-api-design) - [getChatMessage API](#aicoach-service-business-api-getchatmessage-api-design) - [getCoachConversation API](#aicoach-service-business-api-getcoachconversation-api-design) - [getMealPlan API](#aicoach-service-business-api-getmealplan-api-design) - [getModerationRecord API](#aicoach-service-business-api-getmoderationrecord-api-design) - [getMyQuota API](#aicoach-service-business-api-getmyquota-api-design) - [getPlanMeal API](#aicoach-service-business-api-getplanmeal-api-design) - [getProgramExercise API](#aicoach-service-business-api-getprogramexercise-api-design) - [getQuotaConfig API](#aicoach-service-business-api-getquotaconfig-api-design) - [getTrainingProgram API](#aicoach-service-business-api-gettrainingprogram-api-design) - [getUserQuota API](#aicoach-service-business-api-getuserquota-api-design) - [getWeightLog API](#aicoach-service-business-api-getweightlog-api-design) - [listChatMessages API](#aicoach-service-business-api-listchatmessages-api-design) - [listCoachConversations API](#aicoach-service-business-api-listcoachconversations-api-design) - [listMealPlans API](#aicoach-service-business-api-listmealplans-api-design) - [listModerationRecords API](#aicoach-service-business-api-listmoderationrecords-api-design) - [listPlanMeals API](#aicoach-service-business-api-listplanmeals-api-design) - [listProgramExercises API](#aicoach-service-business-api-listprogramexercises-api-design) - [listQuotaConfigs API](#aicoach-service-business-api-listquotaconfigs-api-design) - [listTrainingPrograms API](#aicoach-service-business-api-listtrainingprograms-api-design) - [listUserQuotas API](#aicoach-service-business-api-listuserquotas-api-design) - [listWeightLogs API](#aicoach-service-business-api-listweightlogs-api-design) - [updateQuotaConfig API](#aicoach-service-business-api-updatequotaconfig-api-design) - [deleteModerationRecord API](#aicoach-service-business-api-deletemoderationrecord-api-design) - [deletemealplan API](#aicoach-service-business-api-deletemealplan-api-design) - [deletetrainingprogram API](#aicoach-service-business-api-deletetrainingprogram-api-design) - [updateModerationRecord API](#aicoach-service-business-api-updatemoderationrecord-api-design) - [listmymoderationrecords API](#aicoach-service-business-api-listmymoderationrecords-api-design) - [listBanAppeals API](#aicoach-service-business-api-listbanappeals-api-design) - [createBanAppeal API](#aicoach-service-business-api-createbanappeal-api-design) - [updateBanAppeal API](#aicoach-service-business-api-updatebanappeal-api-design) - [createAdditionalQuota API](#aicoach-service-business-api-createadditionalquota-api-design) - [getMyAdditionalQuota API](#aicoach-service-business-api-getmyadditionalquota-api-design) - [getAdditionalQuotaPayment API](#aicoach-service-business-api-getadditionalquotapayment-api-design) - [listAdditionalQuotaPayments API](#aicoach-service-business-api-listadditionalquotapayments-api-design) - [createAdditionalQuotaPayment API](#aicoach-service-business-api-createadditionalquotapayment-api-design) - [updateAdditionalQuotaPayment API](#aicoach-service-business-api-updateadditionalquotapayment-api-design) - [deleteAdditionalQuotaPayment API](#aicoach-service-business-api-deleteadditionalquotapayment-api-design) - [getAdditionalQuotaPaymentByOrderId API](#aicoach-service-business-api-getadditionalquotapaymentbyorderid-api-design) - [getAdditionalQuotaPaymentByPaymentId API](#aicoach-service-business-api-getadditionalquotapaymentbypaymentid-api-design) - [startAdditionalQuotaPayment API](#aicoach-service-business-api-startadditionalquotapayment-api-design) - [refreshAdditionalQuotaPayment API](#aicoach-service-business-api-refreshadditionalquotapayment-api-design) - [callbackAdditionalQuotaPayment API](#aicoach-service-business-api-callbackadditionalquotapayment-api-design) - [getPaymentCustomerByUserId API](#aicoach-service-business-api-getpaymentcustomerbyuserid-api-design) - [listPaymentCustomers API](#aicoach-service-business-api-listpaymentcustomers-api-design) - [listPaymentCustomerMethods API](#aicoach-service-business-api-listpaymentcustomermethods-api-design) - [Service Library](#aicoach-service-service-library) ### Subscription Service - [Service Design](#subscription-service-service-design) - [REST API Guide](#subscription-service-rest-api-guide) - [Event Guide](#subscription-service-event-guide) - **Data Objects** - [pricingConfig Design](#subscription-service-pricingconfig-design) - [subscription Design](#subscription-service-subscription-design) - [sys_subscriptionPayment Design](#subscription-service-sys-subscriptionpayment-design) - [sys_paymentCustomer Design](#subscription-service-sys-paymentcustomer-design) - [sys_paymentMethod Design](#subscription-service-sys-paymentmethod-design) - **Business APIs** - [cancelSubscription API](#subscription-service-business-api-cancelsubscription-api-design) - [checkSubscriptionStatus API](#subscription-service-business-api-checksubscriptionstatus-api-design) - [createPricingConfig API](#subscription-service-business-api-createpricingconfig-api-design) - [deletePricingConfig API](#subscription-service-business-api-deletepricingconfig-api-design) - [getMySubscription API](#subscription-service-business-api-getmysubscription-api-design) - [getPricingConfig API](#subscription-service-business-api-getpricingconfig-api-design) - [getSubscription API](#subscription-service-business-api-getsubscription-api-design) - [listPricingConfigs API](#subscription-service-business-api-listpricingconfigs-api-design) - [listSubscriptions API](#subscription-service-business-api-listsubscriptions-api-design) - [updatePricingConfig API](#subscription-service-business-api-updatepricingconfig-api-design) - [createSubscription API](#subscription-service-business-api-createsubscription-api-design) - [test API](#subscription-service-business-api-test-api-design) - [getSubscriptionPayment API](#subscription-service-business-api-getsubscriptionpayment-api-design) - [listSubscriptionPayments API](#subscription-service-business-api-listsubscriptionpayments-api-design) - [createSubscriptionPayment API](#subscription-service-business-api-createsubscriptionpayment-api-design) - [updateSubscriptionPayment API](#subscription-service-business-api-updatesubscriptionpayment-api-design) - [deleteSubscriptionPayment API](#subscription-service-business-api-deletesubscriptionpayment-api-design) - [getSubscriptionPaymentByOrderId API](#subscription-service-business-api-getsubscriptionpaymentbyorderid-api-design) - [getSubscriptionPaymentByPaymentId API](#subscription-service-business-api-getsubscriptionpaymentbypaymentid-api-design) - [startSubscriptionPayment API](#subscription-service-business-api-startsubscriptionpayment-api-design) - [refreshSubscriptionPayment API](#subscription-service-business-api-refreshsubscriptionpayment-api-design) - [callbackSubscriptionPayment API](#subscription-service-business-api-callbacksubscriptionpayment-api-design) - [getPaymentCustomerByUserId API](#subscription-service-business-api-getpaymentcustomerbyuserid-api-design) - [listPaymentCustomers API](#subscription-service-business-api-listpaymentcustomers-api-design) - [listPaymentCustomerMethods API](#subscription-service-business-api-listpaymentcustomermethods-api-design) - [Service Library](#subscription-service-service-library) ### AgentHub Service - [Service Design](#agenthub-service-service-design) - [REST API Guide](#agenthub-service-rest-api-guide) - [Event Guide](#agenthub-service-event-guide) - **Data Objects** - [sys_agentOverride Design](#agenthub-service-sys-agentoverride-design) - [sys_agentExecution Design](#agenthub-service-sys-agentexecution-design) - [sys_toolCatalog Design](#agenthub-service-sys-toolcatalog-design) - **Business APIs** - [getAgentOverride API](#agenthub-service-business-api-getagentoverride-api-design) - [listAgentOverrides API](#agenthub-service-business-api-listagentoverrides-api-design) - [updateAgentOverride API](#agenthub-service-business-api-updateagentoverride-api-design) - [createAgentOverride API](#agenthub-service-business-api-createagentoverride-api-design) - [deleteAgentOverride API](#agenthub-service-business-api-deleteagentoverride-api-design) - [listToolCatalog API](#agenthub-service-business-api-listtoolcatalog-api-design) - [getToolCatalogEntry API](#agenthub-service-business-api-gettoolcatalogentry-api-design) - [listAgentExecutions API](#agenthub-service-business-api-listagentexecutions-api-design) - [getAgentExecution API](#agenthub-service-business-api-getagentexecution-api-design) ### Bff Service - [Service Design](#bff-service-service-design) - [REST API Guide](#bff-service-rest-api-guide) - [Event Guide](#bff-service-event-guide) ### Notification Service - [Service Design](#notification-service-service-design) - [REST API Guide](#notification-service-rest-api-guide) - [Event Guide](#notification-service-event-guide) ### LLM Documents - [Documentation Index](#llm-llms) - [Complete Documentation](#llm-llms-full) - [REST API Reference](#llm-llms-restapi) - [Frontend Prompts](#llm-llms-prompts) --- # Getting Started ## AI Fitness & Nutrition Coach # AI Fitness & Nutrition Coach Version : 1.0.146 aifitapp is a subscription-based, AI-powered fitness and nutrition platform that generates personalized training programs and dietary plans using evidence-based principles. Users interact with an intelligent chatbot to receive customized workout regimes, meal recommendations, exercise and food alternatives, and educational guidance—all governed by strict safety and scientific protocols. ## How to Use Project Documents The `Aifitapp` project has been designed and generated using **Mindbricks**, a powerful microservice-based backend generation platform. All documentation is automatically produced by the **Mindbricks Genesis Engine**, based on the high-level architectural patterns defined by the user or inferred by AI. This documentation set is intended for both **AI agents** and **human developers**—including frontend and backend engineers—who need precise and structured information about how to interact with the backend services of this project. Each document reflects the live architecture of the system, providing a reliable reference for API consumption, data models, authentication flows, and business logic. By following this documentation, developers can seamlessly integrate with the backend, while AI agents can use it to reason about the service structure, make accurate decisions, or even generate compatible client-side code. ## Accessing Project Services Each service generated by Mindbricks is exposed via a **dedicated REST API** endpoint. Every service documentation set includes the **base URL** of that service along with the **specific API paths** for each available route. Before consuming any API, developers or agents must understand the service URL structure and environment-specific endpoints. ### Service Endpoint Structure | Environment | URL Pattern Example | |-------------|---------------------| | **Preview** | `https://appaili.prw.mindbricks.com/auth-api` | | **Staging** | `https://appaili-stage.mindbricks.co/auth-api` | | **Production** | `https://appaili.mindbricks.co/auth-api` | Replace `auth` with the actual service name as lower case (e.g., `order-api`, `bff-service`, customermanagement-api etc.). ### Environment Usage Notes * **Preview APIs** become accessible after a project is previewed inside the Mindbricks platform. These are ideal for development and testing. * **Staging** and **Production** APIs are only accessible after the project is deployed to cloud environments provisioned via Mindbricks. * In some cases, the project owner may choose to deploy services on their **own infrastructure**. In such scenarios, the service base URLs will be **custom** and should be communicated manually by the project owner to developers or AI agents. > **Frontend applications** should be designed to **easily switch between environments**, allowing dynamic endpoint targeting for Preview, Staging, and Production. ## Getting Started: Use the Auth Service First Before interacting with other services in the `Aifitapp` project, **AI agents and developers should begin by integrating with the Auth Service**. Mindbricks automatically generates a dedicated authentication microservice based on the project’s authentication definitions provided by the architect. This service provides the essential user and access management foundation for the project. Agents should first utilize the Auth Service to: * Register and authenticate users (login) * Manage users, roles, and permissions * Handle user groups (if defined) * Support multi-tenancy logic (if configured) * Perform Policy-Based Access Control (PBAC), if activated by the architect ### Auth Service Documentation Use the following resources to understand and integrate the Auth Service: * **REST API Guide** – ideal for frontend and direct HTTP usage [Auth REST API Guide](/document/docs/auth-service/rest-api-guide.html) * **Event Guide** – helpful for event-driven or cross-service integrations [Auth Event Guide](/document/docs/auth-service/event-guide.html) * **Service Design Document** – overall structure, patterns, and logic [Auth Service Design](/document/docs/auth-service/service-design.html) > **Note:** For most frontend use cases, the **REST API Guide** will be the primary source. The **Event Guide** and **Service Design** documents are especially useful when integrating with other backend microservices or building systems that interact with the auth service indirectly. ## Using the BFF (Backend-for-Frontend) Service In Mindbricks, all backend services are designed with an advanced **CQRS (Command Query Responsibility Segregation)** architecture. Within this architecture, **business services** are responsible for managing their respective domains and ensuring the accuracy and freshness of domain data. The **BFF service** complements these business services by providing a **read-only** aggregation and query layer tailored specifically for frontend and client-side applications. ### Key Principles of the BFF Service * **Elasticsearch Replicas for Fast Queries:** Each data object managed by a business service is automatically replicated as an **Elasticsearch index**, making it accessible for fast, frontend-oriented queries through the BFF. * **Cross-Service Data Aggregation:** The BFF offers an **aggregation layer** capable of combining data across multiple services, enabling complex filters, searches, and unified views of related data. * **Read-Only by Design:** The BFF service is **strictly read-only**. All create, update, or delete operations must be performed through the relevant business services, or via event-driven sagas if designed. ### BFF Service Documentation * **REST API Guide** – querying aggregated and indexed data [BFF REST API Guide](/document/docs/bff-service/rest-api-guide.html) * **Event Guide** – syncing strategies across replicas [BFF Event Guide](/document/docs/bff-service/event-guide.html) * **Service Design** – aggregation patterns and index structures [BFF Service Design](/document/docs/bff-service/service-design.html) > **Tip:** Use the BFF service as the **main entry point for all frontend data queries**. It simplifies access, reduces round-trips, and ensures that data is shaped appropriately for the UI layer. ## Business Services Overview The `AI Fitness & Nutrition Coach` project consists of multiple **business services**, each responsible for managing a specific domain within the system. These services expose their own REST APIs and documentation sets, and are accessible based on the environment (Preview, Staging, Production). ### Usage Guidance Business services are primarily designed to: * Handle the **state and operations of domain data** * Offer **Create, Update, Delete** operations over owned entities * Serve **direct data queries** (`get`, `list`) for their own objects when needed For advanced query needs across multiple services or aggregated views, prefer using the [BFF service](#using-the-bff-backend-for-frontend-service). ### Available Business Services ### aiCoach Service **Description:** 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 **Documentation:** * [REST API Guide](/document/docs/aiCoach-service/rest-api-guide.html) * [Event Guide](/document/docs/aiCoach-service/event-guide.html) * [Service Design](/document/docs/aiCoach-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://appaili.prw.mindbricks.com/aicoach-api` | | **Staging** | `https://appaili-stage.mindbricks.co/aicoach-api` | | **Production** | `https://appaili.mindbricks.co/aicoach-api` | ### subscription Service **Description:** Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z **Documentation:** * [REST API Guide](/document/docs/subscription-service/rest-api-guide.html) * [Event Guide](/document/docs/subscription-service/event-guide.html) * [Service Design](/document/docs/subscription-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://appaili.prw.mindbricks.com/subscription-api` | | **Staging** | `https://appaili-stage.mindbricks.co/subscription-api` | | **Production** | `https://appaili.mindbricks.co/subscription-api` | ### agentHub Service **Description:** AI Agent Hub **Documentation:** * [REST API Guide](/document/docs/agentHub-service/rest-api-guide.html) * [Event Guide](/document/docs/agentHub-service/event-guide.html) * [Service Design](/document/docs/agentHub-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://appaili.prw.mindbricks.com/agenthub-api` | | **Staging** | `https://appaili-stage.mindbricks.co/agenthub-api` | | **Production** | `https://appaili.mindbricks.co/agenthub-api` | ## Connect via MCP (Model Context Protocol) All backend services in the `Aifitapp` project expose their Business APIs as **MCP tools**. These tools are aggregated by the **MCP-BFF** service into a single unified endpoint that external AI tools can connect to. ### Unified MCP Endpoint | Environment | StreamableHTTP (recommended) | SSE (legacy fallback) | |-------------|------------------------------|------------------------| | **Preview** | `https://appaili.prw.mindbricks.com/mcpbff-api/mcp` | `https://appaili.prw.mindbricks.com/mcpbff-api/mcp/sse` | | **Staging** | `https://appaili-stage.mindbricks.co/mcpbff-api/mcp` | `https://appaili-stage.mindbricks.co/mcpbff-api/mcp/sse` | | **Production** | `https://appaili.mindbricks.co/mcpbff-api/mcp` | `https://appaili.mindbricks.co/mcpbff-api/mcp/sse` | ### Authentication MCP connections require authentication via the `Authorization` header: - **API Key (recommended for AI agents):** `Authorization: Bearer sk_mbx_your_api_key_here` API keys are long-lived and don't expire like JWT tokens. Create one from the profile page. - **JWT Token:** `Authorization: Bearer {accessToken}` Use a valid access token obtained from the login API. > **OAuth is not supported** for MCP connections at this time. ### Connecting from Cursor Add the following to your project's `.cursor/mcp.json`: ```json { "mcpServers": { "appaili": { "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer sk_mbx_your_api_key_here" } } } } ``` ### Connecting from Claude Desktop Add to your Claude Desktop configuration (`claude_desktop_config.json`): ```json { "mcpServers": { "appaili": { "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer sk_mbx_your_api_key_here" } } } } ``` ### What's Available Once connected, the AI tool can discover and call all Business API tools from all services — CRUD operations, custom queries, file operations, and more. The MCP-BFF handles routing each tool call to the correct backend service and propagates your authentication context. --- ## Conclusion This documentation set provides a comprehensive guide for understanding and consuming the `AI Fitness & Nutrition Coach` backend, generated by the Mindbricks platform. It is structured to support both AI agents and human developers in navigating authentication, data access, service responsibilities, and system architecture. To summarize: * Start with the **Auth Service** to manage users, roles, sessions, and permissions. * Use the **BFF Service** for optimized, read-only data queries and cross-service aggregation. * Refer to the **Business Services** when you need to manage domain-specific data or perform direct CRUD operations. Each service offers a complete set of documentation—REST API guides, event interface definitions, and design insights—to help you integrate efficiently and confidently. Whether you are building a frontend application, configuring an automation agent, or simply exploring the architecture, this documentation is your primary reference for working with the backend of this project. > For environment-specific access, ensure you're using the correct base URLs (Preview, Staging, Production), and coordinate with the project owner for any custom deployments. --- # Frontend Prompts ## Project Introduction & Setup # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Project Introduction & Setup** This is the introductory document for the **aifitapp** frontend project. It is designed for AI agents that will generate frontend code to consume the project's backend. Read it carefully — it describes the project scope, architecture, API conventions, and initial screens you must build before proceeding to the feature-specific prompts that follow. This prompt will help you set up the project infrastructure, create the initial layout, home page, navigation, and any dummy screens. The subsequent prompts will provide detailed API documentation for each feature area. ## Project Introduction aifitapp is a subscription-based, AI-powered fitness and nutrition platform that generates personalized training programs and dietary plans using evidence-based principles. Users interact with an intelligent chatbot to receive customized workout regimes, meal recommendations, exercise and food alternatives, and educational guidance—all governed by strict safety and scientific protocols. ## Project Services Overview The project has **1 auth service**, **1 notification service**, **1 BFF service**, and **3 business services**, plus other helper services such as bucket and realtime. Each service is a separate microservice application and listens for HTTP requests at different service URLs. | # | Service | Description | API Prefix | |---|---------|-------------|------------| | 1 | auth | Authentication and user management | `/auth-api` | | 2 | aiCoach | 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 | `/aiCoach-api` | | 3 | subscription | Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z | `/subscription-api` | | 4 | agentHub | AI Agent Hub | `/agentHub-api` | Detailed API documentation for each service will be given in the following prompts. In this document, you will build the initial project structure, home pages, and navigation. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API's response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## Accessing the Backend Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services. The base URL of the application in each environment is as follows: * **Preview:** `https://appaili.prw.mindbricks.com` * **Staging:** `https://appaili-stage.mindbricks.co` * **Production:** `https://appaili.mindbricks.co` For the auth service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/auth-api` * **Staging:** `https://appaili-stage.mindbricks.co/auth-api` * **Production:** `https://appaili.mindbricks.co/auth-api` For each other service, append `/{serviceName}-api` to the environment base URL. Any request that requires login must include a valid token in the Bearer authorization header. Please note that for each service in the project (which will be introduced in following prompts) will use a different address so it is a good practice to define a separate client for each service in the frontend application lib source. Not only the different base urls, some services even may need different access rules when shaping the request. Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page. ## Home Page First build a home page which shows some static content about the application, and has got login and registration (if is public) buttons. The home page should be updated later according to the content that each service provides, as a frontend developer use best and common practices to reflect the service content to the home page. User may also give extra information for the home page content in addition to this prompt. Note that this page should include a deployment (environment) selection option to set the base URL. Set the default to `production`. After user logs in, page header should show the current login state as in modern web pages, logged in user fullname, avatar, email and with a logout link, make a fancy current user component. The home page may have different views before and after login. ## Initial Navigation Structure Build the initial navigation/sidebar with placeholder pages for each area of the application. These will be implemented in detail by the subsequent prompts: - Home / Landing - Login - Register - Verification - Profile - User Management (admin) - AiCoach Service Pages - Subscription Service Pages - AgentHub Service Pages Create these as placeholder/dummy pages with a title and "Coming soon" note. They will be filled in by the following prompts. ## What To Build Now With this prompt, build: 1. **Project infrastructure** — routing, layout, environment config, API client setup (one client per service) 2. **Home page** with environment selector, login/register buttons, project description 4. **Placeholder pages** for all navigation items listed above 5. **Common components** — header with user info, navigation sidebar/menu, layout wrapper Do **not** implement authentication flows, registration, or any service-specific features yet — those will be covered in the next prompts. ## Common Reminders 1. When the application starts, please ensure that the `baseUrl` is set to the production server URL, and that the environment selector dropdown has the **Production** option selected by default. 2. Note that any API call to the application backend is based on a service base URL. Auth APIs use `/auth-api` prefix, and each business service uses `/{serviceName}-api` prefix after the application's base URL. 3. The deployment environment selector will only be used in the home page. If any page is called directly bypassing the home page, the page will use the stored or default environment. --- ## Authentication Management # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Authentication Management** This document covers the authentication features of the **aifitapp** project: registration, login, logout, and session management. The project introduction, API conventions, base URLs, home page, and multi-tenancy setup were covered in the previous introductory prompt — make sure those are implemented before proceeding. All auth APIs use the auth service base URL with the `/auth-api` prefix (e.g., `https://appaili.mindbricks.co/auth-api`). ### FRONTEND_URL The `FRONTEND_URL` environment variable is automatically set on the auth service from the project's **frontendUrl** setting in Basic Project Settings. It contains the base URL of the frontend application for the current deployment environment (e.g., `http://localhost:5173` for dev, `https://myapp.com` for production). Defaults if not configured: | Environment | Default | |-------------|---------| | dev | `http://localhost:5173` | | test | `https://appaili.prw.mindbricks.com` | | stage | `https://appaili-stage.mindbricks.co` | | prod | `https://appaili.mindbricks.co` | This variable is used by the auth service for: - **Social login redirects** — after OAuth processing, the auth service redirects to `FRONTEND_URL + /auth/callback` (the frontend must have a page at this route; see the Social Login prompt for details) - **Email notification links** — verification, password reset, and other links in emails point back to the frontend You can customize `FRONTEND_URL` per environment by configuring the `frontendUrl` field in your project's Basic Project Settings (e.g., when using a custom domain). ## Registration Management ### User Registration User registration is public in the application. Please create a simple and polished registration page that includes only the necessary fields of the registration API. Using the `registeruser` route of the auth API, send the required fields from your registration page. The `registerUser` API in the `auth` service is described with the request and response structure below. Note that since the `registerUser` API is a business API, it is versioned; call it with the given version like `/v1/registeruser`. ### `Register User` API This api is used by public users to register themselves **Rest Route** The `registerUser` API REST controller can be triggered via the following route: `/v1/registeruser` **Rest Request Parameters** The `registerUser` api has got 15 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | email | String | true | request.body?.["email"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | true | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **password** : The password defined by the the user that is being registered. **fullname** : The fullname defined by the the user that is being registered. **email** : The email defined by the the user that is being registered. **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/registeruser** ```js axios({ method: 'POST', url: '/v1/registeruser', data: { avatar:"String", password:"String", fullname:"String", email:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` After a successful registration, the frontend code should handle any verification requirements. Verification Management will be given in the next prompt. The registration response will include a `user` object in the root envelope; this object contains user information with an `id` field. ## Login Management ### Login Identifier Model The **primary login identifier** for this application is the **email address**. Users register and log in using their email and password. No mobile field is stored in the user data model. The login page should include an email input and a password input. ### Login Flow After successful registration and completing any required verifications, the user can log in. Please create a minimal, polished login page as described above. Note that this page should respect the deployment (environment) selection option made in the home page to set the base URL. If the user reaches this page directly skipping home page, the default `production` deployment will be used. The login API returns a created session. This session can be retrieved later with the access token using the `/currentuser` system route. Any request that requires login must include a valid token. When a user logs in successfully, the response JSON includes a JWT access token in the `accessToken` field. Under normal conditions, this token is also set as a cookie and consumed automatically. However, since AI coding agents' preview options may fail to use cookies, ensure that each request includes the access token in the Bearer authorization header. If the login fails due to verification requirements, the response JSON includes an `errCode`. If it is `EmailVerificationNeeded`, start the email verification flow; if it is `MobileVerificationNeeded`, start the mobile verification flow. After a successful login, you can access session (user) information at any time with the `/currentuser` API. On inner pages, show brief profile information (avatar, name, etc.) using the session information from this API. Note that the `currentuser` API returns a session object, so there is no `id` property; instead, the values for the user and session are exposed as `userId` and `sessionId`. The response combines user and session information. The login, logout, and currentuser APIs are as follows. They are system routes and are not versioned. ### `POST /login` — User Login **Purpose:** Verifies user credentials and creates an authenticated session with a JWT access token. **Access Routes:** #### Request Parameters | Parameter | Type | Required | Source | | ---------- | ------ | -------- | ----------------------- | | `username` | String | Yes | `request.body.username` | | `password` | String | Yes | `request.body.password` | #### Behavior * Authenticates credentials and returns a session object. * Sets cookie: `projectname-access-token[-tenantCodename]` * Adds the same token in response headers. * Accepts either `username` or `email` fields (if both exist, `username` is prioritized). The `mobile` field is also accepted when the user has a mobile number on file. #### Example ```js axios.post("/login", { email: "user@example.com", password: "securePassword" }); ``` #### Success Response ```json { "sessionId": "e81c7d2b-4e95-9b1e-842e-3fb9c8c1df38", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", //... "accessToken": "ey7....", "userBucketToken": "e56d....", "sessionNeedsEmail2FA": true, "sessionNeedsMobile2FA": true, } ``` > **Note on bucket tokens:** The `userBucketToken` is for the **external bucket service** (used for general file uploads like documents and product images). **User avatars do not use the external bucket service** — they are uploaded via database buckets (dbBuckets) built into the auth service using the regular `accessToken`. See the Profile or Bucket Management sections for dbBucket avatar upload details. > **Two-Factor Authentication (2FA):** When the login response contains `sessionNeedsEmail2FA: true or sessionNeedsMobile2FA: true`, the session is **not yet fully authorized**. The `accessToken` is valid but all protected API calls will return `403` until 2FA is completed. **Do not treat this login as successful** — instead, store the `accessToken`, `userId`, and `sessionId`, and navigate the user to a 2FA verification page. The 2FA flow details are covered in the **Verification Management** prompt. ### Error Responses * `401 Unauthorized`: Invalid credentials * `403 Forbidden`: Email/mobile verification or 2FA pending * `400 Bad Request`: Missing parameters --- ### `POST /logout` — User Logout **Purpose:** Terminates the current session and clears associated authentication tokens. #### Behavior * Invalidates the session (if it exists). * Clears cookie `projectname-access-token[-tenantCodename]`. * Returns a confirmation response (always `200 OK`). #### Example ```js axios.post("/logout", {}, { headers: { "Authorization": "Bearer your-jwt-token" } }); ``` #### Notes * Can be called without a session (idempotent behavior). * Works for both cookie-based and token-based sessions. #### Success Response ```json { "status": "OK", "message": "User logged out successfully" } ``` ### `GET /currentuser` — Current Session **Purpose** Returns the currently authenticated user's session. **Route Type** `sessionInfo` **Authentication** Requires a valid access token (header or cookie). #### Request *No parameters.* #### Example ```js axios.get("/currentuser", { headers: { Authorization: "Bearer " } }); ``` #### Success (200) Returns the session object (identity, tenancy, token metadata): ```json { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", "...": "..." } ``` Note that the `currentuser` API returns a session object, so there is no `id` property, instead, the values for the user and session are exposed as `userId` and `sessionId`. The response is a mix of user and session information. #### Errors * **401 Unauthorized** — No active session/token ```json { "status": "ERR", "message": "No login found" } ``` **Notes** * Commonly called by web/mobile clients after login to hydrate session state. * Includes key identity/tenant fields and a token reference (if applicable). * Ensure a valid token is supplied to receive a 200 response. After you complete this step, please ensure you have not made the following common mistakes: 1. The `/currentuser` API returns a mix of session and user data. There is no `id` property —use `userId` and `sessionId`. 2. Note that any API call to the auth service should use the `/auth-api` prefix after the application's base URL. **After this prompt, the user may give you new instructions to update your output or provide subsequent prompts about the project.** --- ## Verification Management # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Verification Management** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document includes the verification processes for the autheitcation flow. Please read it carefully and implement all requirements described here. The project has 1 auth service, 1 notification service, 1 BFF service, and 3 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service. Each service is a separate microservice application and listens for HTTP requests at different service URLs. Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page. ## Accessing the backend Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services. For the auth service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/auth-api` * **Staging:** `https://appaili-stage.mindbricks.co/auth-api` * **Production:** `https://appaili.mindbricks.co/auth-api` Any request that requires login must include a valid token in the Bearer authorization header. ## After User Registration Frontend should also be aware of verification after any login attempt. The login request may return a 401 or 403 with the error codes that indicates the verification needs. ```json { //... "errCode": "EmailVerificationNeeded", // or "errCode": "MobileVerificationNeeded", } ``` ## Email Verification In the registration response, check the `emailVerificationNeeded` property in the response root. If it is `true`, start the email verification flow. After the login process, if you receive an HTTP error and the response contains an `errCode` with the value `EmailVerificationNeeded`, start the email verification flow. 1. Call the email verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the provided email address. **The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the `secretCode` property of the response.** 2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. **If the `secretCode` is sent to the frontend for testing, display it on the input page so the user can copy and paste it.** 3. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index in the message with the one on the screen. 4. When the user submits the code, complete the email verification using the `complete` route of the backend (described below) with the user's email and the secret code. 5. After a successful email verification response, please check the response object to have the property 'mobileVerificationNeeded' as `true`, if so navigate to the mobile verification flow as described below. **If no mobile verification is needed then just navigate the login page.** Below are the `start` and `complete` routes for email verification. These are system routes and therefore are not versioned. #### `POST /verification-services/email-verification/start` **Purpose:** Starts email verification by generating and sending a secret code. | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------ | | `email` | String | Yes | User's email address to verify | **Example Request** ```json { "email": "user@example.com" } ``` **Success Response** ```json { "status": "OK", "codeIndex": 1, // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)", // expireTime: in seconds "expireTime": 86400, "verificationType": "byLink", // in testMode "secretCode": "123456", "userId": "user-uuid" } ``` > ⚠️ In production, `secretCode` is **not** returned — it is only sent via email. **Error Responses** * `400 Bad Request`: Already verified * `403 Forbidden`: Too many attempts (rate limit) --- #### `POST /verification-services/email-verification/complete` **Purpose:** Completes verification using the received code. | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ----------------- | | `email` | String | Yes | User's email | | `secretCode` | String | Yes | Verification code | **Success Response** ```json { "status": "OK", "isVerified": true, "email": "user@email.com", // in testMode "userId": "user-uuid" } ``` **Error Responses** * `403 Forbidden`: Code expired or mismatched * `404 Not Found`: No verification in progress --- ## Mobile Verification > **Mobile numbers must be in E.164 format** (`+` followed by country code and subscriber number, e.g. `+905551234567`). Use the `PhoneInput` component for mobile number inputs on verification pages. In the registration response, check the `mobileVerificationNeeded` property in the response root. If it is `true`, start the mobile verification flow. After the login process, if you receive a 403 error and the response contains an `errCode` with the value `MobileVerificationNeeded`, start the mobile verification flow. 1. Call the mobile verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the user's mobile number. **If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the `secretCode` property.** 2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. **If the `secretCode` is returned for testing, display it on the input page for easy copy/paste.** 3. When the user submits the code, complete mobile verification using the `complete` route of the backend (described below) with the user's email and the secret code. 4. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index shown in the message with the one on the screen. 5. After a successful mobile verification response, navigate to the login page. **Verification Order** If both `emailVerificationNeeded` and `mobileVerificationNeeded` are `true`, handle both verification flows in order. First complete email verification, then mobile verification. Below are the `start` and `complete` routes for mobile verification. These are system routes and therefore are not versioned. #### `POST /verification-services/mobile-verification/start` | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------ | | `email` | String | Yes | User's email to locate mobile record | **Success Response** ```json { "status": "OK", "codeIndex": 1, // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)", // expireTime: in seconds "expireTime": 180, "verificationType": "byCode", // in testMode "secretCode": "123456", "userId": "user-uuid" } ``` > ⚠️ `secretCode` is returned only in development. **Errors** * `400 Bad Request`: Already verified * `403 Forbidden`: Rate-limited --- #### `POST /verification-services/mobile-verification/complete` | Parameter | Type | Required | Description | | ------------ | ------ | -------- | --------------------- | | `email` | String | Yes | Associated email | | `secretCode` | String | Yes | Code received via SMS | **Success Response** ```json { "status": "OK", "isVerified": true, "mobile": "+1 333 ...", // in testMode "userId": "user-uuid" } ``` --- ## Resetting Password Users can reset their forgotten passwords without a login required, through email and mobile verification. To be able to start a password reset flow, users will click on the "Reset Password" link in the login page. Since there are two verification methods, by email or by mobile, for password reset, when the reset password link is clicked, frontend should ask user if they want to make the verification through email of mobile. According to the users selection the frontend shoudl start the related flow as explaned below step by step. ## Password Reset By Email Flow 1. Call the password reset by email verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the provided email address. **The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the `secretCode` property of the response.** 2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. **If the `secretCode` is sent to the frontend for testing, display it on the input page so the user can copy and paste it.** 3. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index in the message with the one on the screen. 4. The input page should also include a double input area for the user to enter and confirm their new password. 5. When the user submits the code and the new password, complete the password reset by email using the `complete` route of the backend (described below) with the user's email , the secret code and new password. 6. After a successful verification response, navigate to the login page. Below are the `start` and `complete` routes for password reset by email verification. These are system routes and therefore are not versioned. #### POST `/verification-services/password-reset-by-email/start` **Purpose**: Starts the password reset process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address of the user | ```json { "email": "user@example.com" } ``` **Success Response** Returns secret code details (only in development environment) and confirmation that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "codeIndex": 1, "secretCode": "123456", "timeStamp": 1765484354, "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z", "verificationType": "byLink", } ``` ⚠️ In production, the secret code is only sent via email and not exposed in the API response. **Error Responses** - `401 NotAuthenticated`: Email address not found or not associated with a user. - `403 Forbidden`: Sending a code too frequently (spam prevention). --- #### POST `/verification-services/password-reset-by-email/complete` **Purpose**: Completes the password reset process by validating the secret code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|----------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via email | | password | String | Yes | The new password the user wants to set | ```json { "email": "user@example.com", "secretCode": "123456", "password": "newSecurePassword123" } ``` **Success Response** ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ``` **Error Responses** - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Password Reset By Mobile Flow 1. Call the password reset by mobile verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the user's mobile number. **If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the `secretCode` property.** 2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. **If the `secretCode` is returned for testing, display it on the input page for easy copy/paste.** 3. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index in the message with the one on the screen. Also display the half masked `mobile`number that comes in the response, to tell the user that their code is sent to this number. 4. The input page should also include a double input area for the user to enter and confirm their new password. 5. When the user submits the code, complete mobile verification using the `complete` route of the backend (described below) with the user's email and the secret code. 6. After a successful mobile verification response, navigate to the login page. Below are the `start` and `complete` routes for password reset by mobile verification. These are system routes and therefore are not versioned. #### POST `/verification-services/password-reset-by-mobile/start` **Purpose**: Initiates the mobile-based password reset by sending a verification code to the user's mobile. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|------------------------------| | email | String | Yes | The email of the user that resets the password | ```json { "email": "user@user.com" } ``` ### Success Response Returns the verification context (code returned only in development): ```json { "status": "OK", "codeIndex": 1, timeStamp: 133241255, "mobile": "+905.....67", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z", verificationType: "byLink" } ``` ⚠️ In production, the `secretCode` is not included in the response and is only sent via SMS. ### Error Responses - **400 Bad Request**: Mobile already verified - **403 Forbidden**: Rate-limited (code already sent recently) - **404 Not Found**: User with provided mobile not found --- #### POST `/verification-services/password-reset-by-mobile/complete` **Purpose**: Finalizes the password reset process by validating the received verification code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via SMS | | password | String | Yes | The new password to assign | ```json { "email": "user@example.com", "secretCode": "123456", "password": "NewSecurePassword123!" } ``` ### Success Response ```json { "userId": "user-uuid", "isVerified": true } ``` --- ## Two-Factor Authentication (2FA) **This project has email and mobile two-factor authentication enabled.** 2FA is different from email/mobile verification: verification proves ownership during registration (one-time), while **2FA runs on every login** as an additional security layer. ### How 2FA Works After Login When a user logs in successfully, the login response includes `accessToken`, `userId`, `sessionId`, and all session data. However, when 2FA is active, the response **also** contains one or both of these flags: * `sessionNeedsEmail2FA: true` — email 2FA is required * `sessionNeedsMobile2FA: true` — mobile 2FA is required **When any of these flags are `true`, the session is NOT fully authorized.** The `accessToken` is valid only for calling the 2FA verification endpoints. All other protected API calls will return `403 Forbidden` with error code `EmailTwoFactorNeeded` or `MobileTwoFactorNeeded` until 2FA is completed. ### 2FA Frontend Flow 1. After a successful login, check the response for `sessionNeedsEmail2FA` or `sessionNeedsMobile2FA`. 2. If either is `true`, **do not treat the user as authenticated**. Store the `accessToken`, `userId`, and `sessionId` temporarily. 3. Navigate the user to a **2FA verification page**. 4. On the 2FA page, immediately call the 2FA `start` endpoint (described below) with the `userId` and `sessionId`. This triggers sending the verification code to the user's email or mobile. 5. Display a 6-digit code input. **If the response contains `secretCode` (test/development mode), display it on the page so the user can copy and paste it.** 6. The `start` response includes a `codeIndex` property. Display its value on the page so the user can match the index in the message with the one on the screen. 7. When the user submits the code, call the 2FA `complete` endpoint with `userId`, `sessionId`, and `secretCode`. 8. On success, the `complete` endpoint returns the **updated session object** with the 2FA flag cleared. Now set the user as fully authenticated and navigate to the main application page. 9. Provide a "Resend Code" button with a **60-second cooldown** to prevent spam. 10. Provide a "Cancel" option that discards the partial session and returns the user to the login page. ### 2FA Type Selection When both email and mobile 2FA are enabled, the login response may have both `sessionNeedsEmail2FA: true` and `sessionNeedsMobile2FA: true`. In this case, handle email 2FA first, then mobile 2FA — similar to the verification order for email and mobile verification. ### Email 2FA Endpoints #### `POST /verification-services/email-2factor-verification/start` **Purpose:** Starts email-based 2FA by generating and sending a verification code to the user's email. | Parameter | Type | Required | Description | | ----------- | ------ | -------- | ------------------------------ | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The current session ID | **Example Request** ```json { "userId": "user-uuid", "sessionId": "session-uuid" } ``` **Success Response** ```json { "status": "OK", "sessionId": "session-uuid", "userId": "user-uuid", "codeIndex": 1, "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300", "expireTime": 86400, "verificationType": "byCode", // in testMode only "secretCode": "123456" } ``` > ⚠️ In production, `secretCode` is **not** returned — it is only sent via email. **Error Responses** * `403 Forbidden`: Code resend attempted before cooldown (60s) * `401 Unauthorized`: Session not found --- #### `POST /verification-services/email-2factor-verification/complete` **Purpose:** Completes email 2FA by validating the code and clearing the session 2FA flag. | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ----------------------------- | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The session ID | | `secretCode` | String | Yes | Verification code from email | **Success Response** Returns the updated session with `sessionNeedsEmail2FA: false`: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "sessionNeedsEmail2FA": false, "accessToken": "jwt-token", "...": "..." } ``` **Error Responses** * `403 Forbidden`: Code mismatch or expired * `403 Forbidden`: No ongoing verification found * `401 Unauthorized`: Session does not exist --- ### Mobile 2FA Endpoints > **Important:** Mobile 2FA requires that the user has a **verified mobile number**. If the user's mobile is not verified, the start endpoint will return a `403` error. #### `POST /verification-services/mobile-2factor-verification/start` **Purpose:** Starts mobile-based 2FA by generating and sending a verification code via SMS. | Parameter | Type | Required | Description | | ----------- | ------ | -------- | ------------------------------ | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The current session ID | **Example Request** ```json { "userId": "user-uuid", "sessionId": "session-uuid" } ``` **Success Response** ```json { "status": "OK", "sessionId": "session-uuid", "userId": "user-uuid", "codeIndex": 1, "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300", "expireTime": 300, "verificationType": "byCode", // in testMode only "secretCode": "654321" } ``` > ⚠️ In production, `secretCode` is **not** returned — it is only sent via SMS. **Error Responses** * `403 Forbidden`: Mobile number not verified * `403 Forbidden`: Code resend attempted before cooldown (60s) * `401 Unauthorized`: Session not found --- #### `POST /verification-services/mobile-2factor-verification/complete` **Purpose:** Completes mobile 2FA by validating the code and clearing the session 2FA flag. | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ---------------------------- | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The session ID | | `secretCode` | String | Yes | Code received via SMS | **Success Response** Returns the updated session with `sessionNeedsMobile2FA: false`: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "mobile": "+15551234567", "fullname": "John Doe", "roleId": "user", "sessionNeedsMobile2FA": false, "accessToken": "jwt-token", "...": "..." } ``` **Error Responses** * `403 Forbidden`: Code mismatch or expired * `403 Forbidden`: No ongoing verification found * `401 Unauthorized`: Session does not exist --- ### Important 2FA Notes * **One code per session**: Only one active verification code exists per session at a time. * **Resend throttling**: Code requests are throttled — wait at least 60 seconds between resend attempts. * **Code expiration**: Codes expire after 86400 seconds. * **Session stays valid**: The `accessToken` from login remains the same throughout the 2FA flow — you do not get a new token. The `complete` response returns the same session with the 2FA flag cleared. * **`/currentuser` works during 2FA**: The `/currentuser` endpoint does **not** enforce 2FA, so it can be called during the 2FA flow. However, all other protected endpoints will return `403`. ** Please dont forget to arrange the code to be able to navigate to the verification pages both after registrations and login attempts if verification is needed.** **After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.** --- ## Profile Management # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - Profile Management** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document includes information and api descriptions about building a **profile page** in the frontend using the auth service profile api calls. Avatar images are stored in the auth service's database buckets — no external bucket service is needed for avatars. The project has 1 auth service, 1 notification service, 1 BFF service, and 3 business services, plus other helper services such as bucket and realtime. In this document you will use the auth service (including its database bucket endpoints for avatar uploads). Each service is a separate microservice application and listens for HTTP requests at different service URLs. Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page. ## Accessing the backend Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the register and login pages include a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services. The base URL of the application in each environment is as follows: * **Preview:** `https://appaili.prw.mindbricks.com` * **Staging:** `https://appaili-stage.mindbricks.co` * **Production:** `https://appaili.mindbricks.co` For the auth service, service urls are as follows: * **Preview:** `https://appaili.prw.mindbricks.com/auth-api` * **Staging:** `https://appaili-stage.mindbricks.co/auth-api` * **Production:** `https://appaili.mindbricks.co/auth-api` For each other service, the service URL will be given in the service sections. Any request that requires login must include a valid token in the Bearer authorization header. ## Avatar Storage (Database Buckets) User avatars and tenant avatars are stored directly in the auth service database using **database buckets** (dbBuckets). This means avatar files are uploaded to and downloaded from the **auth service itself** — no external bucket service is needed. The auth service provides these avatar buckets: ### User Avatar Bucket **Upload:** `POST {authBaseUrl}/bucket/userAvatars/upload` **Download by ID:** `GET {authBaseUrl}/bucket/userAvatars/download/{fileId}` **Download by Key:** `GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}` - **Read access:** Public (anyone can view avatars, no auth needed for download) - **Write access:** Authenticated (any logged-in user can upload their own avatar) - **Allowed types:** image/png, image/jpeg, image/webp, image/gif - **Max size:** 5 MB - **Access key:** Each uploaded file gets a 12-character random key for shareable links **Upload example (multipart/form-data):** ```js const formData = new FormData(); formData.append('file', croppedImageBlob, 'avatar.png'); const response = await fetch(`${authBaseUrl}/bucket/userAvatars/upload`, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, }, body: formData, }); const result = await response.json(); // result.file.id — the file ID (use for download URL) // result.file.accessKey — 12-char key for public sharing // result.file.fileName, result.file.mimeType, result.file.fileSize ``` **After uploading, update the user's avatar field** with the download URL: ```js const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/${result.file.id}`; // OR use the access key for a shorter, shareable URL: const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`; await updateProfile({ avatar: avatarUrl }); ``` **Displaying avatars:** Since read access is public, avatar URLs can be used directly in `` tags without any authentication token: ```jsx Avatar ``` ### Listing and Deleting Avatars The auth service also provides metadata APIs for each bucket (auto-generated): | API | Method | Path | Description | |-----|--------|------|-------------| | `getUserAvatarsFile` | GET | `/v1/userAvatarsFiles/:id` | Get file metadata (no binary) | | `listUserAvatarsFiles` | GET | `/v1/userAvatarsFiles` | List files with filtering | | `deleteUserAvatarsFile` | DELETE | `/v1/userAvatarsFiles/:id` | Delete file and its data | ## Profile Page Design a profile page to manage (view and edit) user information. The profile page should include an avatar upload component that uploads to the database bucket. On the profile page, you will need 4 business APIs: `getUser` , `updateProfile`, `updateUserPassword` and `archiveProfile`. Do not rely on the `/currentuser` response for profile data, because it contains session information. The most recent user data is in the user database and should be accessed via the `getUser` business API. The `updateProfile`, `updateUserPassword` and `archiveProfile` api can only be called by the users themselves. They are designed specific to the profile page. **Avatar upload workflow:** 1. User selects an image → crop with `react-easy-crop` (install it, do not implement your own) 2. Convert cropped area to a Blob 3. Upload to `POST {authBaseUrl}/bucket/userAvatars/upload` with the access token 4. Get back the file metadata (id, accessKey) 5. Construct the download URL: `{authBaseUrl}/bucket/userAvatars/download/key/{accessKey}` 6. Call `updateProfile({ avatar: downloadUrl })` to save it **Note that the user cannot change/update their `email` or `roleId`.** For password update you should make a separate block in the UI, so that user can enter old password, new password and confirm new password before calling the `updateUserPassword`. Here are the 3 auth APIs—`getUser` , `updateProfile` and `updateUserPassword`— as follows: You can access these APIs through the auth service base URL, `{appUrl}/auth-api`. ### `Get User` API This api is used by admin roles or the users themselves to get the user profile information. **Rest Route** The `getUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `getUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users/:userId** ```js axios({ method: 'GET', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Profile` API This route is used by users to update their profiles. **Rest Route** The `updateProfile` API REST controller can be triggered via the following route: `/v1/profile/:userId` **Rest Request Parameters** The `updateProfile` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | false | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/profile/:userId** ```js axios({ method: 'PATCH', url: `/v1/profile/${userId}`, data: { fullname:"String", avatar:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpassword` API This route is used to update the password of users in the profile page by users themselves **Rest Route** The `updateUserPassword` API REST controller can be triggered via the following route: `/v1/userpassword/:userId` **Rest Request Parameters** The `updateUserPassword` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | oldPassword | String | true | request.body?.["oldPassword"] | | newPassword | String | true | request.body?.["newPassword"] | **userId** : This id paremeter is used to select the required data object that will be updated **oldPassword** : The old password of the user that will be overridden bu the new one. Send for double check. **newPassword** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpassword/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpassword/${userId}`, data: { oldPassword:"String", newPassword:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Archiving A Profile A user may want to archive their profile. So the profile page should include an archive section for the users to archive their accounts. When an account is archived, it is marked as archived and an aarchiveDate is atteched to the profile. All user data is kept in the database for 1 month after user archived. If user tries to login or register with the same email, the account will be activated again. But if no login or register occures in 1 month after archiving, the profile and its related data will be deleted permanenetly. So in the profile page, 1. The arcihve options should be accepted after user writes a text like ("ARCHİVE MY ACCOUNT") to a confirmation dialog, so that frontend UX can ensure this is not an unconscious request. 2. The user should be warned about the process, that his account will be available for a restore for 1 month. The archive api, can only be called by the users themselves and its used as follows. ### `Archive Profile` API This api is used by users to archive their profiles. **Rest Route** The `archiveProfile` API REST controller can be triggered via the following route: `/v1/archiveprofile/:userId` **Rest Request Parameters** The `archiveProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/archiveprofile/:userId** ```js axios({ method: 'DELETE', url: `/v1/archiveprofile/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- After you complete this step, please ensure you have not made the following common mistakes: 1. Avatar uploads go to the **auth service's database bucket** endpoints (`/bucket/userAvatars/upload`), not to an external bucket service. Use the same `accessToken` (Bearer header) for both auth APIs and avatar bucket uploads — no bucket-specific tokens are needed. 2. Note that any api call to the application backend is based on a service base url, in this prompt all auth apis (including avatar bucket endpoints) should be called by the auth service base url. 3. On the profile page, fetch the latest user data from the service using `getUser`. The `/currentuser` API is session-stored data; the latest data is in the database. 4. When you upload the avatar image on the profile page, use the returned download URL as the user's `avatar` property and update the user record when the Save button is clicked. **After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.** --- ## User Management # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - User Management** This document is the 2nd part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document provides extensive instruction for administrative user management. ## Service Access User management is handled through auth service again. Auth service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the auth service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/auth-api` * **Staging:** `https://appaili-stage.mindbricks.co/auth-api` * **Production:** `https://appaili.mindbricks.co/auth-api` Please note that any feature in this document is open to admins only. When the user logins, the response includes a roleId field. This roleId should one of these following admin roles. `superAdmin`, `admin`, ## Scope Auth service provides following feature for user management in aifitapp application. These features are already handled in the previous part. 1. User Registration 2. User Authentication 3. Password Reset 3. Email (and/or) Mobile Verification 4. Profile Management These features will be handled in this part. - User Management - User Groups Management - Permission Manageemnt ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API's response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## User Management User management will be one of the main parts of the administrative manageemnts, so there will be a minimal but fancy `users` page in the admin dashboard. ### User Roles - `superadmin` : The first creator of the backend, the owner of the application, root user, has got an absolute authroization on all actions. It can not be assgined any other user. It can't be unassigned. Super admin user can not be deleted in any way. - `admin` : The role that can be assigned to any user by the super admin. This role includes most permissions that super admin have, but admins can't assign admin roles, can't unassign an admin role, can't delete other users who have admin role. In addition to these limitations, some critical actions in the business services may also be open to only super admin. - `user` : The standard role that is assgined to every user when first created or registered. This role doesnt have any privilages and can access to their own data or public data. The roles object is a hardcoded object in the generated code, and it contains the following roles: ```json { "superAdmin": "'superAdmin'", "admin": "'admin'", "user": "'user'" } ``` Each user may have only one role, and it is given in `/login` , `/currentuser` or `/users/:userId` response as follows ```json { // ... "roleId":"superAdmin", // ... } ``` ## Listing Users You can list users using the `listUsers` api. ### `List Users` API The list of users is filtered by the tenantId. **Rest Route** The `listUsers` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** **Filter Parameters** The `listUsers` api supports 8 optional filter parameters for filtering list results: **email** (`String`): A string value to represent the user's email. - Single (partial match, case-insensitive): `?email=` - Multiple: `?email=&email=` - Null: `?email=null` **fullname** (`String`): A string value to represent the fullname of the user - Single (partial match, case-insensitive): `?fullname=` - Multiple: `?fullname=&fullname=` - Null: `?fullname=null` **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **activityLevel** (`Enum`): User's general daily activity level, used as the TDEE activity multiplier. - Single: `?activityLevel=` (case-insensitive) - Multiple: `?activityLevel=&activityLevel=` - Null: `?activityLevel=null` **country** (`String`): User's country of residence, used for regional food suggestions and cuisine preferences. - Single (partial match, case-insensitive): `?country=` - Multiple: `?country=&country=` - Null: `?country=null` **fitnessGoal** (`Enum`): User's primary fitness goal driving program and nutrition recommendations. - Single: `?fitnessGoal=` (case-insensitive) - Multiple: `?fitnessGoal=&fitnessGoal=` - Null: `?fitnessGoal=null` **sex** (`Enum`): User's biological sex, used for BMR calculations and program customization. - Single: `?sex=` (case-insensitive) - Multiple: `?sex=&sex=` - Null: `?sex=null` **trainingExperience** (`Enum`): User's training experience level, influencing program complexity and progression rates. - Single: `?trainingExperience=` (case-insensitive) - Multiple: `?trainingExperience=&trainingExperience=` - Null: `?trainingExperience=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users** ```js axios({ method: 'GET', url: '/v1/users', data: { }, params: { // Filter parameters (see Filter Parameters section above) // email: '' // Filter by email // fullname: '' // Filter by fullname // roleId: '' // Filter by roleId // activityLevel: '' // Filter by activityLevel // country: '' // Filter by country // fitnessGoal: '' // Filter by fitnessGoal // sex: '' // Filter by sex // trainingExperience: '' // Filter by trainingExperience } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ## Searching Users You may search users with their full names, emails. The search is done in elasticsearch index of the user table so a fast response is provided by the backend. You can send search request on each character update in the search box but start searching after 3 chars. The keyword parameter that is used in the business logic of the api, is read from the keyword query parameter. eg: `GET /v1/searchusers?keyword=Joe` When the user deletes the search keyword, use the `listUsers` api to get the full list again. ### `Search Users` API The list of users is filtered by the tenantId. **Rest Route** The `searchUsers` API REST controller can be triggered via the following route: `/v1/searchusers` **Rest Request Parameters** The `searchUsers` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | keyword | String | true | request.query?.["keyword"] | **keyword** : **Filter Parameters** The `searchUsers` api supports 6 optional filter parameters for filtering list results: **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **activityLevel** (`Enum`): User's general daily activity level, used as the TDEE activity multiplier. - Single: `?activityLevel=` (case-insensitive) - Multiple: `?activityLevel=&activityLevel=` - Null: `?activityLevel=null` **country** (`String`): User's country of residence, used for regional food suggestions and cuisine preferences. - Single (partial match, case-insensitive): `?country=` - Multiple: `?country=&country=` - Null: `?country=null` **fitnessGoal** (`Enum`): User's primary fitness goal driving program and nutrition recommendations. - Single: `?fitnessGoal=` (case-insensitive) - Multiple: `?fitnessGoal=&fitnessGoal=` - Null: `?fitnessGoal=null` **sex** (`Enum`): User's biological sex, used for BMR calculations and program customization. - Single: `?sex=` (case-insensitive) - Multiple: `?sex=&sex=` - Null: `?sex=null` **trainingExperience** (`Enum`): User's training experience level, influencing program complexity and progression rates. - Single: `?trainingExperience=` (case-insensitive) - Multiple: `?trainingExperience=&trainingExperience=` - Null: `?trainingExperience=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/searchusers** ```js axios({ method: 'GET', url: '/v1/searchusers', data: { }, params: { keyword:'"String"', // Filter parameters (see Filter Parameters section above) // roleId: '' // Filter by roleId // activityLevel: '' // Filter by activityLevel // country: '' // Filter by country // fitnessGoal: '' // Filter by fitnessGoal // sex: '' // Filter by sex // trainingExperience: '' // Filter by trainingExperience } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` #### Pagination When you list the users please use pagination. To be able to use pagination you should provide a `pageNumber` paramater in the query. The default row count for one page is 25, add an option for user to change it to 50 or 100. You can provide this value to the api through the `pageRowCount` parameter; `GET /users?pageNumber=1&pageRowCount=50` ## Creating Users The user management console in the admin dashboard should provide UX components for user creating by admins. When creating users, it should also be possible to upload user avatar. Note that when creating, updating users, admins can not set emailVerified as true, since it is a logical mechanism and should be verified only through verification processes. ### `Create User` API This api is used by admin roles to create a new user manually from admin panels **Rest Route** The `createUser` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** The `createUser` api has got 15 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | email | String | true | request.body?.["email"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | true | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **email** : A string value to represent the user's email. **password** : A string value to represent the user's password. It will be stored as hashed. **fullname** : A string value to represent the fullname of the user **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/users** ```js axios({ method: 'POST', url: '/v1/users', data: { avatar:"String", email:"String", password:"String", fullname:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Avatar Upload Avatars are stored in the auth service's **database bucket** — no external bucket service needed. Upload the avatar image to the auth service's userAvatars bucket endpoint: `POST {authBaseUrl}/bucket/userAvatars/upload` Use the regular access token (Bearer header) for authentication — the same token used for all other API calls. The upload body is `multipart/form-data` with a `file` field. After upload, the response returns file metadata including `id` and `accessKey`. Construct a public download URL and save it in the user's `avatar` field: ```js const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`; await updateUser(userId, { avatar: avatarUrl }); ``` Since the userAvatars bucket has public read access, avatar URLs work directly in `` tags without auth. Before the avatar upload, use the `react-easy-crop` lib for zoom, pan and crop. This component is also used in the profile page — reuse the existing code. ## Updating Users User update is possible by `updateUser`api. However since this update api is also called by teh user themselves it is lmited with name and avatar change (or any other user related property). For roleId and password updates seperate apis are used. So arrange the user update UI as to update the user info, as to set roleId and as to update password. ### `Update User` API This route is used by admins to update user profiles. **Rest Route** The `updateUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `updateUser` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | false | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/users/:userId** ```js axios({ method: 'PATCH', url: `/v1/users/${userId}`, data: { fullname:"String", avatar:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` For role updates there are some rules. 1. Superadmin role can not be unassigned even by superadmin. 2. Admin roles can be assgined or unassgined only by superadmin. 3. All other roles can be assigned and unassgined by admins and superadmin. For password updates there are some rules. 1. Superadmin and admin passwords can be updated only by superadmin. 2. Admins can update only non-admin passwords. ### `Update Userrole` API This route is used by admin roles to update the user role.The default role is user when a user is registered. A user's role can be updated by superAdmin or admin **Rest Route** The `updateUserRole` API REST controller can be triggered via the following route: `/v1/userrole/:userId` **Rest Request Parameters** The `updateUserRole` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | roleId | String | true | request.body?.["roleId"] | **userId** : This id paremeter is used to select the required data object that will be updated **roleId** : The new roleId of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userrole/:userId** ```js axios({ method: 'PATCH', url: `/v1/userrole/${userId}`, data: { roleId:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpasswordbyadmin` API This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords **Rest Route** The `updateUserPasswordByAdmin` API REST controller can be triggered via the following route: `/v1/userpasswordbyadmin/:userId` **Rest Request Parameters** The `updateUserPasswordByAdmin` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | password | String | true | request.body?.["password"] | **userId** : This id paremeter is used to select the required data object that will be updated **password** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpasswordbyadmin/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpasswordbyadmin/${userId}`, data: { password:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Deleting Users Deleting users is possible in certain conditions. 1. SuperAdmin can not be deleted. 2. Admins can be deleted by only superadmin. 3. Users can be deleted by admins or superadmin. ### `Delete User` API This api is used by admins to delete user profiles. **Rest Route** The `deleteUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `deleteUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/users/:userId** ```js axios({ method: 'DELETE', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- When you list user group members, a `user` object will also be inserted in each userGroupMember object, with fullname, avatar, email. ## Avatar Storage (Database Buckets) (This information is also covered in the Profile prompt.) Avatars are stored in the auth service's **database buckets** — uploaded to and downloaded from the auth service directly using the regular access token. **User Avatar Bucket:** - Upload: `POST {authBaseUrl}/bucket/userAvatars/upload` (multipart/form-data, `file` field) - Download: `GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}` (public, no auth needed) - Allowed: image/png, image/jpeg, image/webp, image/gif (max 5 MB) When uploading an avatar (for user creation or update), send the image to the bucket, get back the `accessKey`, construct the download URL, and store it in the user's `avatar` field via the update API. **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## MCP BFF Integration # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - MCP BFF Integration** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document provides comprehensive instructions for integrating the **MCP BFF** (Model Context Protocol - Backend for Frontend) service into the frontend application. The MCP BFF is the central gateway between the frontend AI chat and all backend services. --- ## MCP BFF Architecture Overview The Aifitapp application uses an **MCP BFF** service that aggregates multiple backend MCP servers into a single frontend-facing API. Instead of the frontend connecting to each service's MCP endpoint directly, it communicates exclusively through the MCP BFF. ``` ┌────────────┐ ┌───────────┐ ┌─────────────────┐ │ Frontend │────▶│ MCP BFF │────▶│ Auth Service │ │ (Chat UI) │ │ :3005 │────▶│ Business Svc 1 │ │ │◀────│ │────▶│ Business Svc N │ └────────────┘ SSE └───────────┘ └─────────────────┘ ``` ### Key Responsibilities - **Tool Aggregation**: Discovers and registers tools from all connected MCP services - **Session Forwarding**: Injects the user's `accessToken` into every MCP tool call - **AI Orchestration**: Routes user messages to the AI model, which decides which tools to call - **SSE Streaming**: Streams chat responses, tool executions, and results to the frontend in real-time - **Elasticsearch**: Provides direct search/aggregation endpoints across all project indices - **Logging**: Provides log viewing and real-time console streaming endpoints ## MCP BFF Service URLs For the MCP BFF service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/mcpbff-api` * **Staging:** `https://appaili-stage.mindbricks.co/mcpbff-api` * **Production:** `https://appaili.mindbricks.co/mcpbff-api` All endpoints below are relative to the MCP BFF base URL. --- ## Authentication All MCP BFF endpoints require authentication. The user's access token (obtained from the Auth service login) must be included in every request: ```js const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}`, }; ``` --- ## Chat API (AI Interaction) The chat API is the primary interface for AI-powered conversations. It supports both regular HTTP responses and **SSE streaming** for real-time output. ### POST /api/chat — Regular Chat Send a message and receive the complete AI response. ```js const response = await fetch(`${mcpBffUrl}/api/chat`, { method: 'POST', headers, body: JSON.stringify({ message: "Show me all orders from last week", conversationId: "optional-conversation-id", // for conversation context context: {} // additional context }), }); ``` ### POST /api/chat/stream — SSE Streaming Chat (Recommended) Stream the AI response in real-time using Server-Sent Events (SSE). This is the recommended approach for chat UIs as it provides immediate feedback while the AI is thinking, calling tools, and generating text. **Request:** ```js const response = await fetch(`${mcpBffUrl}/api/chat/stream`, { method: 'POST', headers, body: JSON.stringify({ message: "Create a new product called Widget", conversationId: conversationId, // optional, auto-generated if omitted disabledServices: [], // optional, service names to exclude }), }); ``` **Response:** The server responds with `Content-Type: text/event-stream`. Each SSE frame follows the standard format: ``` event: \n data: \n \n ``` ### SSE Event Types The streaming endpoint emits the following event types in order: | Event | When | Data Shape | |-------|------|------------| | `start` | First event, once per stream | `{ conversationId, provider, aliasMapSummary }` | | `text` | AI text token streamed (many per response) | `{ content }` | | `tool_start` | AI decided to call a tool | `{ tool }` | | `tool_executing` | Tool invocation started with resolved args | `{ tool, args }` | | `tool_result` | Tool execution completed | `{ tool, result, success, error? }` — **check for `__frontendAction`** | | `error` | Unrecoverable error | `{ message }` | | `done` | Last event, once per stream | `{ conversationId, toolCalls, processingTime, aliasMapSummary }` | ### SSE Event Data Reference **`start`** — Always the first event. Use `conversationId` for subsequent requests in the same conversation. ```json { "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453", "provider": "anthropic", "aliasMapSummary": { "enabled": true, "count": 0, "samples": [] } } ``` **`text`** — Streamed token-by-token as the AI generates its response. Concatenate `content` fields to build the full markdown message. ```json { "content": "Here" } { "content": "'s your" } { "content": " current session info" } ``` **`tool_start`** — The AI decided to call a tool. Use this to show a loading/spinner UI for the tool. ```json { "tool": "currentuser" } ``` **`tool_executing`** — Tool is now executing with these arguments. Use this to display what the tool is doing. ```json { "tool": "currentuser", "args": { "organizationCodename": "babil" } } ``` **`tool_result`** — Tool finished. Check `success` to determine if it succeeded. The `result` field contains the MCP tool response envelope. ```json { "tool": "currentuser", "result": { "success": true, "service": "auth", "tool": "currentuser", "result": { "content": [{ "type": "text", "text": "{...JSON...}" }] } }, "success": true } ``` On failure, `success` is `false` and an `error` string is present: ```json { "tool": "listProducts", "error": "Connection refused", "success": false } ``` **`done`** — Always the last event. Contains a summary of all tool calls made and total processing time in milliseconds. ```json { "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453", "toolCalls": [ { "tool": "currentuser", "result": { "success": true, "..." : "..." } } ], "processingTime": 10026, "aliasMapSummary": { "enabled": true, "count": 6, "samples": [{ "alias": "user_admin_admin_com" }, { "alias": "tenant_admin_admin_com" }] } } ``` **`error`** — Sent when an unrecoverable error occurs (e.g., AI service unavailable). The stream ends after this event. ```json { "message": "AI service not configured. Please configure OPENAI_API_KEY or ANTHROPIC_API_KEY in environment variables" } ``` ### SSE Event Lifecycle A typical conversation stream follows this lifecycle: ``` start ├── text (repeated) ← AI's initial text tokens ├── tool_start ← AI decides to call a tool ├── tool_executing ← tool running with resolved args ├── tool_result ← tool finished ├── text (repeated) ← AI continues writing after tool result ├── tool_start → tool_executing → tool_result ← may repeat ├── text (repeated) ← AI's final text tokens done ``` Multiple tool calls can happen in a single stream. The AI interleaves text and tool calls — text before tools (explanation), tools in the middle (data retrieval), and text after tools (formatted response using the tool results). ### Inline Segment Rendering (Critical UX Pattern) **Tool cards MUST be rendered inline inside the assistant message bubble, at the exact position where they occur in the stream — not grouped at the top, not grouped at the bottom, and not outside the bubble.** The assistant message is an ordered list of **segments**: text segments and tool segments, interleaved in the order they arrive. Each segment appears inside the same message bubble, in sequence: ``` ┌─────────────────────────────────────────────────┐ │ [Rendered Markdown — text before tool call] │ │ │ │ ┌─ Tool Card ─────────────────────────────────┐ │ │ │ 🔧 currentuser ✓ success │ │ │ │ args: { organizationCodename: "babil" } │ │ │ └─────────────────────────────────────────────┘ │ │ │ │ [Rendered Markdown — text after tool call] │ │ │ │ ┌─ Tool Card ─────────────────────────────────┐ │ │ │ 🔧 listProducts ✓ success │ │ │ └─────────────────────────────────────────────┘ │ │ │ │ [Rendered Markdown — final text] │ └─────────────────────────────────────────────────┘ ``` To achieve this, maintain an **ordered segments array**. Each segment is either `{ type: 'text', content: string }` or `{ type: 'tool', ... }`. When SSE events arrive: 1. **`text`** — Append to the last segment if it is a text segment; otherwise push a new text segment. 2. **`tool_start`** — Push a new tool segment (status: `running`). This "cuts" the current text segment — any further `text` events after the tool completes will start a new text segment. 3. **`tool_executing`** — Update the current tool segment with `args`. 4. **`tool_result`** — Update the current tool segment with `result`, `success`, `error`. Check for `__frontendAction`. 5. After `tool_result`, the next `text` event creates a **new** text segment (the AI is now responding after reviewing the tool result). Render the message bubble by mapping over the segments array in order, rendering each text segment as markdown and each tool segment as a collapsible tool card. ### Parsing SSE Events (Frontend Implementation) Use the `fetch` API with a streaming reader. SSE frames can arrive split across chunks, so buffer partial lines: ```js async function streamChat(mcpBffUrl, headers, message, conversationId, onEvent) { const response = await fetch(`${mcpBffUrl}/api/chat/stream`, { method: 'POST', headers, body: JSON.stringify({ message, conversationId }), }); const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const parts = buffer.split('\n\n'); buffer = parts.pop(); // keep incomplete frame in buffer for (const part of parts) { let eventType = 'message'; let dataStr = ''; for (const line of part.split('\n')) { if (line.startsWith('event: ')) { eventType = line.slice(7).trim(); } else if (line.startsWith('data: ')) { dataStr += line.slice(6); } } if (dataStr) { try { const data = JSON.parse(dataStr); onEvent(eventType, data); } catch (e) { console.warn('Failed to parse SSE data:', dataStr); } } } } } ``` ### Building the Segments Array (React Example) ```js // segments: Array<{ type: 'text', content: string } | { type: 'tool', tool, args?, result?, success?, error?, status }> let segments = []; streamChat(mcpBffUrl, headers, userMessage, conversationId, (event, data) => { switch (event) { case 'start': conversationId = data.conversationId; segments = []; break; case 'text': { const last = segments[segments.length - 1]; if (last && last.type === 'text') { last.content += data.content; // append to current text segment } else { segments.push({ type: 'text', content: data.content }); // new text segment } rerenderBubble(segments); break; } case 'tool_start': // push a new tool segment — this "cuts" the text flow segments.push({ type: 'tool', tool: data.tool, status: 'running' }); rerenderBubble(segments); break; case 'tool_executing': { const toolSeg = findLastToolSegment(segments, data.tool); if (toolSeg) toolSeg.args = data.args; rerenderBubble(segments); break; } case 'tool_result': { const toolSeg = findLastToolSegment(segments, data.tool); if (toolSeg) { toolSeg.status = data.success ? 'complete' : 'error'; toolSeg.result = data.result; toolSeg.error = data.error; toolSeg.success = data.success; // Check for frontend action (QR code, data view, payment, secret) toolSeg.frontendAction = extractFrontendAction(data.result); } rerenderBubble(segments); break; } case 'error': segments.push({ type: 'text', content: `**Error:** ${data.message}` }); rerenderBubble(segments); break; case 'done': // Store final metadata (processingTime, aliasMapSummary) for the message finalizeMessage(segments, data); break; } }); function findLastToolSegment(segments, toolName) { for (let i = segments.length - 1; i >= 0; i--) { if (segments[i].type === 'tool' && segments[i].tool === toolName) return segments[i]; } return null; } ``` ### Rendering the Message Bubble Render each segment in order inside a single assistant message bubble: ```jsx function AssistantMessageBubble({ segments }) { return (
{segments.map((segment, i) => { if (segment.type === 'text') { return ; } if (segment.type === 'tool') { if (segment.frontendAction) { return ; } return ; } return null; })}
); } function ToolCard({ segment }) { const isRunning = segment.status === 'running'; const isError = segment.status === 'error'; return (
{isRunning && } {segment.tool} {!isRunning && (isError ? : )}
{segment.args && (
{JSON.stringify(segment.args, null, 2)}
)} {segment.result && (
{JSON.stringify(segment.result, null, 2)}
)} {segment.error &&
{segment.error}
}
); } ``` The tool card should be compact by default (just tool name + status icon) with collapsible sections for args and result, so it doesn't dominate the reading flow. While a tool is running (`status: 'running'`), show a spinner. When complete, show a check or error icon. ### Handling `__frontendAction` in Tool Results When the AI calls certain tools (e.g., QR code, data view, payment, secret reveal), the tool result contains a `__frontendAction` object. This signals the frontend to render a special UI component **inline in the bubble at the tool segment's position** instead of the default collapsible ToolCard. This is already handled in the segments code above — when `segment.frontendAction` is present, render an `ActionCard` instead of a `ToolCard`. The `extractFrontendAction` helper unwraps the action from various MCP response formats: ```js function extractFrontendAction(result) { if (!result) return null; if (result.__frontendAction) return result.__frontendAction; // Unwrap MCP wrapper format: result → result.result → content[].text → JSON let data = result; if (result?.result?.content) data = result.result; if (data?.content && Array.isArray(data.content)) { const textContent = data.content.find(c => c.type === 'text'); if (textContent?.text) { try { const parsed = JSON.parse(textContent.text); if (parsed?.__frontendAction) return parsed.__frontendAction; } catch { /* not JSON */ } } } return null; } ``` ### Frontend Action Types | Action Type | Component | Description | |-------------|-----------|-------------| | `qrcode` | `QrCodeActionCard` | Renders any string value as a QR code card | | `dataView` | `DataViewActionCard` | Fetches a Business API route and renders a grid or gallery | | `payment` | `PaymentActionCard` | "Pay Now" button that opens Stripe checkout modal | #### QR Code Action (`type: "qrcode"`) Triggered by the `showQrCode` MCP tool. Renders a QR code card from any string value. ```json { "__frontendAction": { "type": "qrcode", "value": "https://example.com/invite/ABC123", "title": "Invite Link", "subtitle": "Scan to open" } } ``` #### Data View Action (`type: "dataView"`) Triggered by `showBusinessApiListInFrontEnd` or `showBusinessApiGalleryInFrontEnd`. Frontend calls the provided Business API route using the user's bearer token, then renders: - `viewType: "grid"` as tabular rows/columns - `viewType: "gallery"` as image-first cards ```json { "__frontendAction": { "type": "dataView", "viewType": "grid", "title": "Recent Orders", "serviceName": "commerce", "apiName": "listOrders", "routePath": "/v1/listorders", "httpMethod": "GET", "queryParams": { "pageNo": 1, "pageRowCount": 10 }, "columns": [ { "field": "id", "label": "Order ID" }, { "field": "orderAmount", "label": "Amount", "format": "currency" } ] } } ``` #### Payment Action (`type: "payment"`) Triggered by the `initiatePayment` MCP tool. Renders a payment card with amount and a "Pay Now" button. ```json { "__frontendAction": { "type": "payment", "orderId": "uuid", "orderType": "order", "serviceName": "commerce", "amount": 99.99, "currency": "USD", "description": "Order #abc123" } } ``` ### Conversation Management ```js // List user's conversations GET /api/chat/conversations // Get conversation history GET /api/chat/conversations/:conversationId // Delete a conversation DELETE /api/chat/conversations/:conversationId ``` --- ## MCP Tool Discovery & Direct Invocation The MCP BFF exposes endpoints for discovering and directly calling MCP tools (useful for debugging or building custom UIs). ### GET /api/tools — List All Tools ```js const response = await fetch(`${mcpBffUrl}/api/tools`, { headers }); const { tools, count } = await response.json(); // tools: [{ name, description, inputSchema, service }, ...] ``` ### GET /api/tools/service/:serviceName — List Service Tools ```js const response = await fetch(`${mcpBffUrl}/api/tools/service/commerce`, { headers }); const { tools } = await response.json(); ``` ### POST /api/tools/call — Call a Tool Directly ```js const response = await fetch(`${mcpBffUrl}/api/tools/call`, { method: 'POST', headers, body: JSON.stringify({ toolName: "listProducts", args: { page: 1, limit: 10 }, }), }); const result = await response.json(); ``` ### GET /api/tools/status — Connection Status ```js const status = await fetch(`${mcpBffUrl}/api/tools/status`, { headers }); // Returns health of each MCP service connection ``` ### POST /api/tools/refresh — Reconnect Services ```js await fetch(`${mcpBffUrl}/api/tools/refresh`, { method: 'POST', headers }); // Reconnects to all MCP services and refreshes the tool registry ``` --- ## Elasticsearch API The MCP BFF provides direct access to Elasticsearch for searching, filtering, and aggregating data across all project indices. All Elasticsearch endpoints are under `/api/elastic`. ### GET /api/elastic/allIndices — List Project Indices Returns all Elasticsearch indices belonging to this project (prefixed with `appaili_`). ```js const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers }); // ["appaili_products", "appaili_orders", ...] ``` ### POST /api/elastic/:indexName/rawsearch — Raw Elasticsearch Query Execute a raw Elasticsearch query on a specific index. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/products/rawsearch`, { method: 'POST', headers, body: JSON.stringify({ query: { bool: { must: [ { match: { status: "active" } }, { range: { price: { gte: 10, lte: 100 } } } ] } }, size: 20, from: 0, sort: [{ createdAt: "desc" }] }), }); const { total, hits, aggregations, took } = await response.json(); // hits: [{ _id, _index, _score, _source: { ...document... } }, ...] ``` Note: The index name is automatically prefixed with `appaili_` if not already prefixed. ### POST /api/elastic/:indexName/search — Simplified Search A higher-level search API with built-in support for filters, sorting, and pagination. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/products/search`, { method: 'POST', headers, body: JSON.stringify({ search: "wireless headphones", // Full-text search filters: { status: "active" }, // Field filters sort: { field: "createdAt", order: "desc" }, page: 1, limit: 25, }), }); ``` ### POST /api/elastic/:indexName/aggregate — Aggregations Run aggregation queries for analytics and dashboards. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/orders/aggregate`, { method: 'POST', headers, body: JSON.stringify({ aggs: { status_counts: { terms: { field: "status.keyword" } }, total_revenue: { sum: { field: "amount" } }, monthly_orders: { date_histogram: { field: "createdAt", calendar_interval: "month" } } }, query: { range: { createdAt: { gte: "now-1y" } } } }), }); ``` ### GET /api/elastic/:indexName/mapping — Index Mapping Get the field mapping for an index (useful for building dynamic filter UIs). ```js const mapping = await fetch(`${mcpBffUrl}/api/elastic/products/mapping`, { headers }); ``` ### POST /api/elastic/:indexName/ai-search — AI-Assisted Search Uses the configured AI model to convert a natural-language query into an Elasticsearch query. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/orders/ai-search`, { method: 'POST', headers, body: JSON.stringify({ query: "orders over $100 from last month that are still pending", }), }); // Returns: { total, hits, generatedQuery, ... } ``` --- ## Log API The MCP BFF provides log viewing endpoints for monitoring application behavior. ### GET /api/logs — Query Logs ```js const response = await fetch(`${mcpBffUrl}/api/logs?page=1&limit=50&logType=2&service=commerce&search=payment`, { headers, }); ``` **Query Parameters:** - `page` — Page number (default: 1) - `limit` — Items per page (default: 50) - `logType` — 0=INFO, 1=WARNING, 2=ERROR - `service` — Filter by service name - `search` — Search in subject and message - `from` / `to` — Date range (ISO strings) - `requestId` — Filter by request ID ### GET /api/logs/stream — Real-time Console Stream (SSE) Streams real-time console output from all services via Server-Sent Events. ```js const eventSource = new EventSource(`${mcpBffUrl}/api/logs/stream?services=commerce,auth`, { headers: { 'Authorization': `Bearer ${accessToken}` }, }); eventSource.addEventListener('log', (event) => { const logEntry = JSON.parse(event.data); // { service, timestamp, level, message, ... } }); ``` --- ## Available Services The MCP BFF connects to the following backend services: | Service | Description | |---------|-------------| | `auth` | Authentication, user management, sessions | | `aiCoach` | 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 | | `subscription` | Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z | | `agentHub` | AI Agent Hub | Each service exposes MCP tools that the AI can call through the BFF. Use `GET /api/tools` to discover all available tools at runtime, or `GET /api/tools/service/:serviceName` to list tools for a specific service. --- ## MCP as Internal API Gateway The MCP-BFF service can also be used by the frontend as an **internal API gateway** for tool-based interactions. This is separate from external AI tool connections — it is meant for frontend code that needs to call backend tools programmatically. ### Direct Tool Calls (REST) Use the REST tool invocation endpoints for programmatic access from frontend code: ```js // List all available tools const tools = await fetch(`${mcpBffUrl}/api/tools`, { headers }); // Call a specific tool directly const result = await fetch(`${mcpBffUrl}/api/tools/call`, { method: 'POST', headers, body: JSON.stringify({ toolName: 'listProducts', args: { page: 1, limit: 10 }, }), }); ``` ### AI-Orchestrated Calls (Chat API) For AI-driven interactions, use the chat streaming API documented above (`POST /api/chat/stream`). The AI model decides which tools to call based on the user's message. Both approaches use the user's JWT access token for authentication — the MCP-BFF forwards it to the correct backend service. --- ## MCP Connection Info for Profile Page The user's **profile page** should include an informational section explaining how to connect external AI tools (Cursor, Claude Desktop, Lovable, Windsurf, etc.) to this application's backend via MCP. ### What to Display The MCP-BFF exposes a **unified MCP endpoint** that aggregates tools from all backend services into a single connection point: | Environment | URL | |-------------|-----| | **Preview** | `https://appaili.prw.mindbricks.com/mcpbff-api/mcp` | | **Staging** | `https://appaili-stage.mindbricks.co/mcpbff-api/mcp` | | **Production** | `https://appaili.mindbricks.co/mcpbff-api/mcp` | For legacy MCP clients that don't support StreamableHTTP, an SSE fallback is available at the same URL with `/sse` appended (e.g., `.../mcpbff-api/mcp/sse`). ### Profile Page UI Requirements Add an **"MCP Connection"** or **"Connect External AI Tools"** card/section to the profile page with: 1. **Endpoint URL** — Display the MCP endpoint URL for the current environment with a copy-to-clipboard button. 2. **Ready-to-Copy Configs** — Show copy-to-clipboard config snippets for popular tools: **Cursor** (`.cursor/mcp.json`): ```json { "mcpServers": { "appaili": { "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } } ``` **Claude Desktop** (`claude_desktop_config.json`): ```json { "mcpServers": { "appaili": { "url": "https://appaili.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } } ``` 3. **Auth Note** — Note that users should replace `your_access_token_here` with a valid JWT access token from the login API. 4. **OAuth Note** — Display a note that OAuth authentication is not currently supported for MCP connections. 5. **Available Tools** — Optionally show a summary of available tool categories (e.g., "CRUD operations for all data objects, custom business APIs, file operations") or link to the tools discovery endpoint (`GET /api/tools`). --- **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## AiCoach Service # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - AiCoach Service** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of aiCoach ## Service Access AiCoach service management is handled through service specific base urls. AiCoach service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the aiCoach service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/aicoach-api` * **Staging:** `https://appaili-stage.mindbricks.co/aicoach-api` * **Production:** `https://appaili.mindbricks.co/aicoach-api` ## Scope **AiCoach Service Description** 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 AiCoach service provides apis and business logic for following data objects in aifitapp application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`chatMessage` Data Object**: Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata. **`coachConversation` Data Object**: Chat conversation container per user for the AI fitness coach chatbot. **`mealPlan` Data Object**: 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. **`moderationRecord` Data Object**: Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review. **`planMeal` Data Object**: Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls. **`programExercise` Data Object**: Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls. **`quotaConfig` Data Object**: System-wide message quota configuration. Admin-managed single record that defines message limits per period. **`trainingProgram` Data Object**: 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. **`userQuota` Data Object**: Per-user message quota consumption tracking against the system-wide quota configuration. **`weightLog` Data Object**: User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach. **`banAppeals` Data Object**: **`additionalQuota` Data Object**: **`sys_additionalQuotaPayment` Data Object**: A payment storage object to store the payment life cyle of orders based on additionalQuota object. It is autocreated based on the source object's checkout config **`sys_paymentCustomer` Data Object**: A payment storage object to store the customer values of the payment platform **`sys_paymentMethod` Data Object**: A payment storage object to store the payment methods of the platform customers ## AiCoach Service Frontend Description By The Backend Architect # AI Coach Service - Frontend UX Guide ## Chatbot Interface - The chatbot is the primary interaction surface. Users send messages and receive AI-generated responses. - Every message goes through subscription, ban, and quota validation before processing. - If a message is flagged as off-topic, the user receives a warning. Progressive penalties apply. - AI responses may include tool call results (program/meal plan updates) - display these as structured cards. ## Training Programs & Meal Plans - These are read-only from the user perspective. All modifications happen through the chatbot. - Display programs with exercises grouped by day label. - Display meal plans with meals grouped by meal label. ## Weight Tracking - Users report weight measurements through a simple form or chatbot. - Display weight history as a chart with weekly averages highlighted. ## Quota Display - Show remaining message quota to users so they can manage usage. - When quota is exceeded, display a clear message. ## Moderation - Suspended users see a message about their suspension with expiry time. - Banned users cannot log in at all (handled at auth level). ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## ChatMessage Data Object Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata. ### ChatMessage Data Object Properties ChatMessage data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `content` | Text | false | Yes | No | Message content | | `conversationId` | ID | false | Yes | No | Reference to the parent conversation | | `flagged` | Boolean | false | No | No | True if the message was detected as off-topic or abusive | | `role` | Enum | false | Yes | No | Message sender role | | `toolCallData` | Text | false | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **role**: [user, assistant, system] ### Relation Properties `conversationId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. 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. - **conversationId**: ID has a filter named `conversationId` - **flagged**: Boolean has a filter named `flagged` - **role**: Enum has a filter named `role` ## CoachConversation Data Object Chat conversation container per user for the AI fitness coach chatbot. ### CoachConversation Data Object Properties CoachConversation data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `status` | Enum | false | Yes | No | Conversation status | | `userId` | ID | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [active, closed] ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ### 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. - **status**: Enum has a filter named `status` - **userId**: ID has a filter named `userId` ## MealPlan Data Object 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. ### MealPlan Data Object Properties MealPlan data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `carbGrams` | Float | false | Yes | No | Daily carbohydrate target in grams | | `dailyCalorieTarget` | Integer | false | Yes | No | Daily calorie target in kcal | | `fatGrams` | Float | false | Yes | No | Daily fat target in grams | | `notes` | Text | false | No | No | Additional AI-generated nutritional guidance | | `proteinGrams` | Float | false | Yes | No | Daily protein target in grams | | `restDayCalories` | Integer | false | No | No | Calorie target on rest days | | `restDayCarbGrams` | Float | false | No | No | Carb target on rest days | | `status` | Enum | false | Yes | No | Meal plan status | | `trainingDayCalories` | Integer | false | No | No | Calorie target on training days | | `trainingDayCarbGrams` | Float | false | No | No | Carb target on training days | | `userId` | ID | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [active, archived] ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ### 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. - **status**: Enum has a filter named `status` - **userId**: ID has a filter named `userId` ## ModerationRecord Data Object Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review. ### ModerationRecord Data Object Properties ModerationRecord data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `action` | Enum | false | Yes | No | Moderation action taken | | `offenseType` | String | false | Yes | No | Description of the violation | | `reason` | Text | false | No | No | Detailed reason for the moderation action | | `suspensionExpiresAt` | Date | false | No | No | When a temporary suspension ends (null for lifetime bans and reversals) | | `userId` | ID | false | Yes | No | Reference to the user who was moderated | | `content` | String | false | Yes | No | | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **action**: [suspension24h, suspension1week, lifetimeBan, banReversal] ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. 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. - **action**: Enum has a filter named `action` - **userId**: ID has a filter named `userId` ## PlanMeal Data Object Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls. ### PlanMeal Data Object Properties PlanMeal data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `carbs` | Float | false | Yes | No | Carb grams for this meal | | `fat` | Float | false | Yes | No | Fat grams for this meal | | `foods` | Text | false | Yes | No | Food items and quantities description | | `mealLabel` | String | false | Yes | No | Meal label (e.g. breakfast, lunch, dinner, snack) | | `mealPlanId` | ID | false | Yes | No | Reference to the parent meal plan | | `protein` | Float | false | Yes | No | Protein grams for this meal | | `sortOrder` | Integer | false | Yes | No | Display sort order within the meal plan | | `totalCalories` | Integer | false | Yes | No | Total calories for this meal | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Relation Properties `mealPlanId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. 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. - **mealPlanId**: ID has a filter named `mealPlanId` ## ProgramExercise Data Object Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls. ### ProgramExercise Data Object Properties ProgramExercise data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `dayLabel` | String | false | Yes | No | Training day label (e.g. pushDay, upperA, legDay) | | `exerciseName` | String | false | Yes | No | Name of the exercise | | `movementType` | Enum | false | Yes | No | Movement type classification | | `muscleGroup` | String | false | Yes | No | Target muscle group | | `progressionRule` | Text | false | No | No | Progression instructions (e.g. double progression model) | | `repMax` | Integer | false | Yes | No | Maximum rep target | | `repMin` | Integer | false | Yes | No | Minimum rep target | | `rirTarget` | Integer | false | Yes | No | Reps In Reserve target (0-3) | | `sets` | Integer | false | Yes | No | Number of working sets | | `sortOrder` | Integer | false | Yes | No | Display sort order within the training day | | `trainingProgramId` | ID | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **movementType**: [lengthened, shortened, compound] ### Relation Properties `trainingProgramId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. 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. - **dayLabel**: String has a filter named `dayLabel` - **muscleGroup**: String has a filter named `muscleGroup` - **trainingProgramId**: ID has a filter named `trainingProgramId` ## QuotaConfig Data Object System-wide message quota configuration. Admin-managed single record that defines message limits per period. ### QuotaConfig Data Object Properties QuotaConfig data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `quotaLimit` | Integer | false | Yes | No | Maximum messages allowed per period | | `quotaPeriod` | Enum | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **quotaPeriod**: [daily, weekly, monthly] ## TrainingProgram Data Object 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. ### TrainingProgram Data Object Properties TrainingProgram data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `cardioDurationMinutes` | Integer | false | No | No | Recommended cardio duration in minutes | | `cardioFrequencyPerWeek` | Integer | false | No | No | Recommended cardio sessions per week | | `cardioType` | String | false | No | No | Type of cardio recommended (e.g. zone2) | | `dailyStepTarget` | Integer | false | No | No | Daily step target for NEAT (7000-12000) | | `deloadIntervalWeeks` | Integer | false | No | No | Weeks between deload periods, typically 6-8 | | `notes` | Text | false | No | No | Additional AI-generated notes and guidance | | `splitType` | String | false | Yes | No | Training split type (e.g. fullBody, upperLower, pushPullLegs) | | `status` | Enum | false | Yes | No | Program status | | `userId` | ID | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [active, archived] ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ### 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. - **status**: Enum has a filter named `status` - **userId**: ID has a filter named `userId` ## UserQuota Data Object Per-user message quota consumption tracking against the system-wide quota configuration. ### UserQuota Data Object Properties UserQuota data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `messageCount` | Integer | false | Yes | No | Number of messages consumed in the current period | | `periodEnd` | Date | false | Yes | No | End of the current quota period | | `periodStart` | Date | false | Yes | No | Start of the current quota period | | `userId` | ID | false | Yes | No | 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, formula or session bind is set. ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ### 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. - **userId**: ID has a filter named `userId` ## WeightLog Data Object User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach. ### WeightLog Data Object Properties WeightLog data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `measuredAt` | Date | false | Yes | No | Date and time of measurement | | `userId` | ID | false | Yes | No | Reference to the user who recorded this weight | | `weightKg` | Float | false | Yes | No | Body weight in kilograms | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ## BanAppeals Data Object ### BanAppeals Data Object Properties BanAppeals data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `moderationRecordId` | ID | false | Yes | No | id of the mod record | | `userId` | ID | false | Yes | No | | | `appealReason` | String | false | Yes | No | | | `status` | Enum | false | Yes | No | | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [pending, approved, rejected] ### Relation Properties `moderationRecordId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ## AdditionalQuota Data Object ### AdditionalQuota Data Object Properties AdditionalQuota data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `userId` | String | false | Yes | No | | | `additionalMessage` | Integer | false | Yes | No | | | `status` | Enum | false | Yes | No | | | `currency` | String | false | Yes | No | | | `pricePaid` | Integer | false | Yes | No | | | `statusUpdatedAt` | Date | false | No | No | | | `activatedAt` | Date | false | No | No | | | `cancelledAt` | Date | false | No | No | | | `periodEnd` | Date | false | No | No | | | `periodStart` | Date | false | No | No | | | `paymentConfirmation` | Enum | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [pending, cancelled, failed, active, expired] - **paymentConfirmation**: [pending, processing, paid, canceled] ### 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. - **paymentConfirmation**: Enum has a filter named `paymentConfirmation` ## Sys_additionalQuotaPayment Data Object A payment storage object to store the payment life cyle of orders based on additionalQuota object. It is autocreated based on the source object's checkout config ### Sys_additionalQuotaPayment Data Object Properties Sys_additionalQuotaPayment data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `ownerId` | ID | false | No | No | An ID value to represent owner user who created the order | | `orderId` | ID | false | Yes | No | an ID value to represent the orderId which is the ID parameter of the source additionalQuota object | | `paymentId` | String | false | Yes | No | 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 | false | Yes | No | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | `statusLiteral` | String | false | Yes | No | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | `redirectUrl` | String | false | No | 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, formula or session bind is set. ### 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. - **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 A payment storage object to store the customer values of the payment platform ### Sys_paymentCustomer Data Object Properties Sys_paymentCustomer data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `userId` | ID | false | No | No | An ID value to represent the user who is created as a stripe customer | | `customerId` | String | false | Yes | No | 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 | false | Yes | No | 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, formula or session bind is set. ### 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. - **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 A payment storage object to store the payment methods of the platform customers ### Sys_paymentMethod Data Object Properties Sys_paymentMethod data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `paymentMethodId` | String | false | Yes | No | A string value to represent the id of the payment method on the payment platform. | | `userId` | ID | false | Yes | No | An ID value to represent the user who owns the payment method | | `customerId` | String | false | Yes | No | A string value to represent the customer id which is generated on the payment gateway. | | `cardHolderName` | String | false | No | No | A string value to represent the name of the card holder. It can be different than the registered customer. | | `cardHolderZip` | String | false | No | No | A string value to represent the zip code of the card holder. It is used for address verification in specific countries. | | `platform` | String | false | Yes | No | 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 | false | Yes | No | 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, formula or session bind is set. ### 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. - **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` ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### ChatMessage Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createChatMessage` | `/v1/chatmessages` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getChatMessage` | `/v1/chatmessages/:chatMessageId` | Yes | | List | `listChatMessages` | `/v1/chatmessages` | Yes | ### CoachConversation Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createCoachConversation` | `/v1/coachconversations` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getCoachConversation` | `/v1/coachconversations/:coachConversationId` | Yes | | List | `listCoachConversations` | `/v1/coachconversations` | Yes | ### MealPlan Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | `deletemealplan` | `/v1/deletemealplan/:mealPlanId` | Auto | | Get | `getMealPlan` | `/v1/mealplans/:mealPlanId` | Yes | | List | `listMealPlans` | `/v1/mealplans` | Yes | ### ModerationRecord Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | `updateModerationRecord` | `/v1/moderationrecords/:moderationRecordId` | Auto | | Delete | `deleteModerationRecord` | `/v1/moderationrecords/:moderationRecordId` | Auto | | Get | `getModerationRecord` | `/v1/moderationrecords/:moderationRecordId` | Yes | | List | `listModerationRecords` | `/v1/moderationrecords` | Yes | ### PlanMeal Default APIs **Display Label Property:** `mealLabel` — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references). | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getPlanMeal` | `/v1/planmeals/:planMealId` | Yes | | List | `listPlanMeals` | `/v1/planmeals` | Yes | ### ProgramExercise Default APIs **Display Label Property:** `exerciseName` — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references). | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getProgramExercise` | `/v1/programexercises/:programExerciseId` | Yes | | List | `listProgramExercises` | `/v1/programexercises` | Yes | ### QuotaConfig Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createQuotaConfig` | `/v1/quotaconfigs` | Yes | | Update | `updateQuotaConfig` | `/v1/quotaconfigs/:quotaConfigId` | Yes | | Delete | _none_ | - | Auto | | Get | `getQuotaConfig` | `/v1/quotaconfigs/:quotaConfigId` | Yes | | List | `listQuotaConfigs` | `/v1/quotaconfigs` | Yes | ### TrainingProgram Default APIs **Display Label Property:** `splitType` — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references). | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | `deletetrainingprogram` | `/v1/deletetrainingprogram/:trainingProgramId` | Auto | | Get | `getTrainingProgram` | `/v1/trainingprograms/:trainingProgramId` | Yes | | List | `listTrainingPrograms` | `/v1/trainingprograms` | Yes | ### UserQuota Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getUserQuota` | `/v1/userquotas/:userQuotaId` | Yes | | List | `listUserQuotas` | `/v1/userquotas` | Yes | ### WeightLog Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createWeightLog` | `/v1/weightlogs` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getWeightLog` | `/v1/weightlogs/:weightLogId` | Yes | | List | `listWeightLogs` | `/v1/weightlogs` | Yes | ### BanAppeals Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createBanAppeal` | `/v1/banappeal` | Auto | | Update | `updateBanAppeal` | `/v1/banappeal/:banAppealsId` | Auto | | Delete | _none_ | - | Auto | | Get | _none_ | - | Auto | | List | `listBanAppeals` | `/v1/banappealses` | Auto | ### AdditionalQuota Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAdditionalQuota` | `/v1/additionalquotas` | Auto | | Update | `startAdditionalQuotaPayment` | `/v1/startadditionalquotapayment/:additionalQuotaId` | Auto | | Delete | _none_ | - | Auto | | Get | `getMyAdditionalQuota` | `/v1/myadditionalquota` | Auto | | List | _none_ | - | Auto | ### Sys_additionalQuotaPayment Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAdditionalQuotaPayment` | `/v1/additionalquotapayment` | Auto | | Update | `updateAdditionalQuotaPayment` | `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` | Auto | | Delete | `deleteAdditionalQuotaPayment` | `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` | Auto | | Get | `getAdditionalQuotaPayment` | `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` | Auto | | List | `listAdditionalQuotaPayments` | `/v1/additionalquotapayments` | Auto | ### Sys_paymentCustomer Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getPaymentCustomerByUserId` | `/v1/paymentcustomers/:userId` | Auto | | List | `listPaymentCustomers` | `/v1/paymentcustomers` | Auto | ### Sys_paymentMethod Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | _none_ | - | Auto | | List | `listPaymentCustomerMethods` | `/v1/paymentcustomermethods/:userId` | Auto | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Create Chatmessage` API **[Default create API]** — This is the designated default `create` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send a message to the AI fitness coach. Enforces the full validation chain: subscription check → ban status check → quota check → content flagging → AI processing → tool call execution → quota increment. Returns both the user message and the AI response. **API Frontend Description By The Backend Architect** # Chat Message Creation - This is the primary interaction endpoint for the AI fitness coach. - User sends a message and receives an AI response in the same call. - The response includes the created user message and an aiResponse object containing the AI's reply and any tool calls executed. - If the message is flagged, aiResponse.flagged will be true. - Handle quota exceeded (403) and suspension (403) errors gracefully. **Rest Route** The `createChatMessage` API REST controller can be triggered via the following route: `/v1/chatmessages` **Rest Request Parameters** The `createChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.body?.["conversationId"] | | content | Text | true | request.body?.["content"] | **conversationId** : The conversation to send the message to **content** : The message content **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/chatmessages** ```js axios({ method: 'POST', url: '/v1/chatmessages', data: { conversationId:"ID", content:"Text", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Coachconversation` API **[Default create API]** — This is the designated default `create` API for the `coachConversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new coach conversation. Requires active subscription and no active ban. **Rest Route** The `createCoachConversation` API REST controller can be triggered via the following route: `/v1/coachconversations` **Rest Request Parameters** The `createCoachConversation` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coachconversations** ```js axios({ method: 'POST', url: '/v1/coachconversations', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coachConversation": { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "activeSubscriptions": "Object" } ``` ### `Create Quotaconfig` API **[Default create API]** — This is the designated default `create` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a quota configuration record. Admin only. **Rest Route** The `createQuotaConfig` API REST controller can be triggered via the following route: `/v1/quotaconfigs` **Rest Request Parameters** The `createQuotaConfig` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaLimit | Integer | true | request.body?.["quotaLimit"] | | quotaPeriod | Enum | true | request.body?.["quotaPeriod"] | **quotaLimit** : Maximum messages allowed per period **quotaPeriod** : Period over which the quota is measured **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/quotaconfigs** ```js axios({ method: 'POST', url: '/v1/quotaconfigs', data: { quotaLimit:"Integer", quotaPeriod:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Weightlog` API **[Default create API]** — This is the designated default `create` API for the `weightLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Report a weight measurement. Requires active subscription and no active ban. **Rest Route** The `createWeightLog` API REST controller can be triggered via the following route: `/v1/weightlogs` **Rest Request Parameters** The `createWeightLog` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | measuredAt | Date | true | request.body?.["measuredAt"] | | weightKg | Float | true | request.body?.["weightKg"] | **measuredAt** : Date and time of measurement **weightKg** : Body weight in kilograms **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/weightlogs** ```js axios({ method: 'POST', url: '/v1/weightlogs', data: { measuredAt:"Date", weightKg:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLog", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "weightLog": { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Chatmessage` API **[Default get API]** — This is the designated default `get` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a chat message by ID with parent conversation ownership validation. **Rest Route** The `getChatMessage` API REST controller can be triggered via the following route: `/v1/chatmessages/:chatMessageId` **Rest Request Parameters** The `getChatMessage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | **chatMessageId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/chatmessages/:chatMessageId** ```js axios({ method: 'GET', url: `/v1/chatmessages/${chatMessageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coachconversation` API **[Default get API]** — This is the designated default `get` API for the `coachConversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a conversation by ID. Users see their own, admins can see any. **Rest Route** The `getCoachConversation` API REST controller can be triggered via the following route: `/v1/coachconversations/:coachConversationId` **Rest Request Parameters** The `getCoachConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coachConversationId | ID | true | request.params?.["coachConversationId"] | **coachConversationId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coachconversations/:coachConversationId** ```js axios({ method: 'GET', url: `/v1/coachconversations/${coachConversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coachConversation": { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Mealplan` API **[Default get API]** — This is the designated default `get` API for the `mealPlan` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a meal plan by ID with meals. Users see their own, admins can see any. **Rest Route** The `getMealPlan` API REST controller can be triggered via the following route: `/v1/mealplans/:mealPlanId` **Rest Request Parameters** The `getMealPlan` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.params?.["mealPlanId"] | **mealPlanId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/mealplans/:mealPlanId** ```js axios({ method: 'GET', url: `/v1/mealplans/${mealPlanId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlan", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "mealPlan": { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "meals": [ { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ] } } ``` ### `Get Moderationrecord` API **[Default get API]** — This is the designated default `get` API for the `moderationRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a moderation record by ID. Admin only. **Rest Route** The `getModerationRecord` API REST controller can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` **Rest Request Parameters** The `getModerationRecord` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | **moderationRecordId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'GET', url: `/v1/moderationrecords/${moderationRecordId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Get Myquota` API Get the current user's quota usage for the active period. **Rest Route** The `getMyQuota` API REST controller can be triggered via the following route: `/v1/my-quota` **Rest Request Parameters** The `getMyQuota` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/my-quota** ```js axios({ method: 'GET', url: '/v1/my-quota', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userQuota": { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Planmeal` API **[Default get API]** — This is the designated default `get` API for the `planMeal` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a plan meal by ID with parent ownership validation. **Rest Route** The `getPlanMeal` API REST controller can be triggered via the following route: `/v1/planmeals/:planMealId` **Rest Request Parameters** The `getPlanMeal` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | planMealId | ID | true | request.params?.["planMealId"] | **planMealId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/planmeals/:planMealId** ```js axios({ method: 'GET', url: `/v1/planmeals/${planMealId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "planMeal", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "planMeal": { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Programexercise` API **[Default get API]** — This is the designated default `get` API for the `programExercise` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a program exercise by ID with parent ownership validation. **Rest Route** The `getProgramExercise` API REST controller can be triggered via the following route: `/v1/programexercises/:programExerciseId` **Rest Request Parameters** The `getProgramExercise` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | programExerciseId | ID | true | request.params?.["programExerciseId"] | **programExerciseId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/programexercises/:programExerciseId** ```js axios({ method: 'GET', url: `/v1/programexercises/${programExerciseId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "programExercise", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "programExercise": { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Quotaconfig` API **[Default get API]** — This is the designated default `get` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a quota configuration record. **Rest Route** The `getQuotaConfig` API REST controller can be triggered via the following route: `/v1/quotaconfigs/:quotaConfigId` **Rest Request Parameters** The `getQuotaConfig` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaConfigId | ID | true | request.params?.["quotaConfigId"] | **quotaConfigId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/quotaconfigs/:quotaConfigId** ```js axios({ method: 'GET', url: `/v1/quotaconfigs/${quotaConfigId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Trainingprogram` API **[Default get API]** — This is the designated default `get` API for the `trainingProgram` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a training program by ID. Users see their own programs, admins can see any. **Rest Route** The `getTrainingProgram` API REST controller can be triggered via the following route: `/v1/trainingprograms/:trainingProgramId` **Rest Request Parameters** The `getTrainingProgram` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.params?.["trainingProgramId"] | **trainingProgramId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/trainingprograms/:trainingProgramId** ```js axios({ method: 'GET', url: `/v1/trainingprograms/${trainingProgramId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingProgram", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "trainingProgram": { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "exercises": [ { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ] } } ``` ### `Get Userquota` API **[Default get API]** — This is the designated default `get` API for the `userQuota` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a user quota record. Users see their own, admins can see any. **Rest Route** The `getUserQuota` API REST controller can be triggered via the following route: `/v1/userquotas/:userQuotaId` **Rest Request Parameters** The `getUserQuota` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userQuotaId | ID | true | request.params?.["userQuotaId"] | **userQuotaId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/userquotas/:userQuotaId** ```js axios({ method: 'GET', url: `/v1/userquotas/${userQuotaId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userQuota": { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "additionalQuota": "Object" } ``` ### `Get Weightlog` API **[Default get API]** — This is the designated default `get` API for the `weightLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a weight log entry by ID. **Rest Route** The `getWeightLog` API REST controller can be triggered via the following route: `/v1/weightlogs/:weightLogId` **Rest Request Parameters** The `getWeightLog` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | weightLogId | ID | true | request.params?.["weightLogId"] | **weightLogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/weightlogs/:weightLogId** ```js axios({ method: 'GET', url: `/v1/weightlogs/${weightLogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "weightLog": { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Chatmessages` API **[Default list API]** — This is the designated default `list` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List chat messages for a conversation with parent ownership validation. **Rest Route** The `listChatMessages` API REST controller can be triggered via the following route: `/v1/chatmessages` **Rest Request Parameters** The `listChatMessages` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.query?.["conversationId"] | **conversationId** : The conversation to list messages for **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/chatmessages** ```js axios({ method: 'GET', url: '/v1/chatmessages', data: { }, params: { conversationId:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "chatMessages": [ { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Coachconversations` API **[Default list API]** — This is the designated default `list` API for the `coachConversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List conversations. Users see their own, admins can see all. **Rest Route** The `listCoachConversations` API REST controller can be triggered via the following route: `/v1/coachconversations` **Rest Request Parameters** **Filter Parameters** The `listCoachConversations` api supports 2 optional filter parameters for filtering list results: **status** (`Enum`): Conversation status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this conversation - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coachconversations** ```js axios({ method: 'GET', url: '/v1/coachconversations', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coachConversations": [ { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Mealplans` API **[Default list API]** — This is the designated default `list` API for the `mealPlan` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List meal plans. Users see their own, admins can see all. **Rest Route** The `listMealPlans` API REST controller can be triggered via the following route: `/v1/mealplans` **Rest Request Parameters** **Filter Parameters** The `listMealPlans` api supports 2 optional filter parameters for filtering list results: **status** (`Enum`): Meal plan status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this meal plan - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/mealplans** ```js axios({ method: 'GET', url: '/v1/mealplans', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlans", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "mealPlans": [ { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Moderationrecords` API **[Default list API]** — This is the designated default `list` API for the `moderationRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moderation records. Admin only. Supports filtering by userId and action. **Rest Route** The `listModerationRecords` API REST controller can be triggered via the following route: `/v1/moderationrecords` **Rest Request Parameters** **Filter Parameters** The `listModerationRecords` api supports 2 optional filter parameters for filtering list results: **action** (`Enum`): Moderation action taken - Single: `?action=` (case-insensitive) - Multiple: `?action=&action=` - Null: `?action=null` **userId** (`ID`): Reference to the user who was moderated - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/moderationrecords** ```js axios({ method: 'GET', url: '/v1/moderationrecords', data: { }, params: { // Filter parameters (see Filter Parameters section above) // action: '' // Filter by action // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "moderationRecords": [ { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Planmeals` API **[Default list API]** — This is the designated default `list` API for the `planMeal` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List meals for a meal plan with parent ownership validation. **Rest Route** The `listPlanMeals` API REST controller can be triggered via the following route: `/v1/planmeals` **Rest Request Parameters** The `listPlanMeals` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.query?.["mealPlanId"] | **mealPlanId** : The meal plan ID to list meals for **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/planmeals** ```js axios({ method: 'GET', url: '/v1/planmeals', data: { }, params: { mealPlanId:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "planMeals", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "planMeals": [ { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Programexercises` API **[Default list API]** — This is the designated default `list` API for the `programExercise` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List exercises for a training program. Validates parent program ownership. **Rest Route** The `listProgramExercises` API REST controller can be triggered via the following route: `/v1/programexercises` **Rest Request Parameters** The `listProgramExercises` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.query?.["trainingProgramId"] | **trainingProgramId** : The training program ID to list exercises for **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/programexercises** ```js axios({ method: 'GET', url: '/v1/programexercises', data: { }, params: { trainingProgramId:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "programExercises", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "programExercises": [ { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Quotaconfigs` API **[Default list API]** — This is the designated default `list` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List quota configuration records. **Rest Route** The `listQuotaConfigs` API REST controller can be triggered via the following route: `/v1/quotaconfigs` **Rest Request Parameters** The `listQuotaConfigs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/quotaconfigs** ```js axios({ method: 'GET', url: '/v1/quotaconfigs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "quotaConfigs": [ { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Trainingprograms` API **[Default list API]** — This is the designated default `list` API for the `trainingProgram` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List training programs. Users see their own programs, admins can see all. **Rest Route** The `listTrainingPrograms` API REST controller can be triggered via the following route: `/v1/trainingprograms` **Rest Request Parameters** **Filter Parameters** The `listTrainingPrograms` api supports 2 optional filter parameters for filtering list results: **status** (`Enum`): Program status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this training program - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/trainingprograms** ```js axios({ method: 'GET', url: '/v1/trainingprograms', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingPrograms", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "trainingPrograms": [ { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Userquotas` API **[Default list API]** — This is the designated default `list` API for the `userQuota` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all user quotas. Admin only. **Rest Route** The `listUserQuotas` API REST controller can be triggered via the following route: `/v1/userquotas` **Rest Request Parameters** **Filter Parameters** The `listUserQuotas` api supports 1 optional filter parameter for filtering list results: **userId** (`ID`): Reference to the user whose quota is being tracked - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/userquotas** ```js axios({ method: 'GET', url: '/v1/userquotas', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuotas", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userQuotas": [ { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Weightlogs` API **[Default list API]** — This is the designated default `list` API for the `weightLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List weight log entries. Users see their own, admins see all. **Rest Route** The `listWeightLogs` API REST controller can be triggered via the following route: `/v1/weightlogs` **Rest Request Parameters** The `listWeightLogs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/weightlogs** ```js axios({ method: 'GET', url: '/v1/weightlogs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "weightLogs": [ { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Quotaconfig` API **[Default update API]** — This is the designated default `update` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a quota configuration record. Admin only. **Rest Route** The `updateQuotaConfig` API REST controller can be triggered via the following route: `/v1/quotaconfigs/:quotaConfigId` **Rest Request Parameters** The `updateQuotaConfig` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaConfigId | ID | true | request.params?.["quotaConfigId"] | | quotaLimit | Integer | false | request.body?.["quotaLimit"] | | quotaPeriod | Enum | false | request.body?.["quotaPeriod"] | **quotaConfigId** : This id paremeter is used to select the required data object that will be updated **quotaLimit** : Maximum messages allowed per period **quotaPeriod** : Period over which the quota is measured **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/quotaconfigs/:quotaConfigId** ```js axios({ method: 'PATCH', url: `/v1/quotaconfigs/${quotaConfigId}`, data: { quotaLimit:"Integer", quotaPeriod:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Moderationrecord` API **Rest Route** The `deleteModerationRecord` API REST controller can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` **Rest Request Parameters** The `deleteModerationRecord` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | **moderationRecordId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'DELETE', url: `/v1/moderationrecords/${moderationRecordId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `Do Deletemealplan` API **Rest Route** The `deletemealplan` API REST controller can be triggered via the following route: `/v1/deletemealplan/:mealPlanId` **Rest Request Parameters** The `deletemealplan` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.params?.["mealPlanId"] | **mealPlanId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/deletemealplan/:mealPlanId** ```js axios({ method: 'DELETE', url: `/v1/deletemealplan/${mealPlanId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlan", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "mealPlan": { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Do Deletetrainingprogram` API **Rest Route** The `deletetrainingprogram` API REST controller can be triggered via the following route: `/v1/deletetrainingprogram/:trainingProgramId` **Rest Request Parameters** The `deletetrainingprogram` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.params?.["trainingProgramId"] | **trainingProgramId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/deletetrainingprogram/:trainingProgramId** ```js axios({ method: 'DELETE', url: `/v1/deletetrainingprogram/${trainingProgramId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingProgram", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "trainingProgram": { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Moderationrecord` API **Rest Route** The `updateModerationRecord` API REST controller can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` **Rest Request Parameters** The `updateModerationRecord` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | | action | String | true | request.body?.["action"] | | content | String | false | request.body?.["content"] | **moderationRecordId** : This id paremeter is used to select the required data object that will be updated **action** : **content** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'PATCH', url: `/v1/moderationrecords/${moderationRecordId}`, data: { action:"String", content:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Do Listmymoderationrecords` API **Rest Route** The `listmymoderationrecords` API REST controller can be triggered via the following route: `/v1/listmymoderationrecords` **Rest Request Parameters** **Filter Parameters** The `listmymoderationrecords` api supports 1 optional filter parameter for filtering list results: **action** (`Enum`): Moderation action taken - Single: `?action=` (case-insensitive) - Multiple: `?action=&action=` - Null: `?action=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/listmymoderationrecords** ```js axios({ method: 'GET', url: '/v1/listmymoderationrecords', data: { }, params: { // Filter parameters (see Filter Parameters section above) // action: '' // Filter by action } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "moderationRecords": [ { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Banappeals` API **Rest Route** The `listBanAppeals` API REST controller can be triggered via the following route: `/v1/banappealses` **Rest Request Parameters** The `listBanAppeals` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | false | request.query?.["userId"] | | status | ID | false | request.query?.["status"] | **userId** : **status** : **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/banappealses** ```js axios({ method: 'GET', url: '/v1/banappealses', data: { }, params: { userId:'"ID"', status:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppealses", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "banAppealses": [ { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "showmoderationRecord": [ { "offenseType": "String", "reason": "Text", "userId": "ID", "content": "String" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Banappeal` API **Rest Route** The `createBanAppeal` API REST controller can be triggered via the following route: `/v1/banappeal` **Rest Request Parameters** The `createBanAppeal` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.body?.["moderationRecordId"] | | appealReason | String | true | request.body?.["appealReason"] | | status | Enum | true | request.body?.["status"] | **moderationRecordId** : id of the mod record **appealReason** : **status** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/banappeal** ```js axios({ method: 'POST', url: '/v1/banappeal', data: { moderationRecordId:"ID", appealReason:"String", status:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppeals", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "banAppeals": { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Banappeal` API **Rest Route** The `updateBanAppeal` API REST controller can be triggered via the following route: `/v1/banappeal/:banAppealsId` **Rest Request Parameters** The `updateBanAppeal` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | banAppealsId | ID | true | request.params?.["banAppealsId"] | | status | Enum | true | request.body?.["status"] | | moderationRecordId | ID | false | request.body?.["moderationRecordId"] | | appealReason | String | false | request.body?.["appealReason"] | **banAppealsId** : This id paremeter is used to select the required data object that will be updated **status** : **moderationRecordId** : id of the mod record **appealReason** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/banappeal/:banAppealsId** ```js axios({ method: 'PATCH', url: `/v1/banappeal/${banAppealsId}`, data: { status:"Enum", moderationRecordId:"ID", appealReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppeals", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "banAppeals": { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Additionalquota` API **Rest Route** The `createAdditionalQuota` API REST controller can be triggered via the following route: `/v1/additionalquotas` **Rest Request Parameters** The `createAdditionalQuota` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalMessage | Integer | true | request.body?.["additionalMessage"] | | status | Enum | true | request.body?.["status"] | | currency | String | true | request.body?.["currency"] | | pricePaid | Integer | true | request.body?.["pricePaid"] | | statusUpdatedAt | Date | false | request.body?.["statusUpdatedAt"] | | activatedAt | Date | false | request.body?.["activatedAt"] | | cancelledAt | Date | false | request.body?.["cancelledAt"] | | periodEnd | Date | false | request.body?.["periodEnd"] | | periodStart | Date | false | request.body?.["periodStart"] | **additionalMessage** : **status** : **currency** : **pricePaid** : **statusUpdatedAt** : **activatedAt** : **cancelledAt** : **periodEnd** : **periodStart** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/additionalquotas** ```js axios({ method: 'POST', url: '/v1/additionalquotas', data: { additionalMessage:"Integer", status:"Enum", currency:"String", pricePaid:"Integer", statusUpdatedAt:"Date", activatedAt:"Date", cancelledAt:"Date", periodEnd:"Date", periodStart:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Myadditionalquota` API **Rest Route** The `getMyAdditionalQuota` API REST controller can be triggered via the following route: `/v1/myadditionalquota` **Rest Request Parameters** The `getMyAdditionalQuota` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myadditionalquota** ```js axios({ method: 'GET', url: '/v1/myadditionalquota', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "myaddQuota": "Object" } ``` ### `Get Additionalquotapayment` API This route is used to get the payment information by ID. **Rest Route** The `getAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` **Rest Request Parameters** The `getAdditionalQuotaPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | **sys_additionalQuotaPaymentId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'GET', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Additionalquotapayments` API This route is used to list all payments. **Rest Route** The `listAdditionalQuotaPayments` API REST controller can be triggered via the following route: `/v1/additionalquotapayments` **Rest Request Parameters** **Filter Parameters** The `listAdditionalQuotaPayments` api supports 6 optional filter parameters for filtering list results: **ownerId** (`ID`): An ID value to represent owner user who created the order - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source additionalQuota object - Single: `?orderId=` - Multiple: `?orderId=&orderId=` - Null: `?orderId=null` **paymentId** (`String`): 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 - Single (partial match, case-insensitive): `?paymentId=` - Multiple: `?paymentId=&paymentId=` - Null: `?paymentId=null` **paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. - Single (partial match, case-insensitive): `?paymentStatus=` - Multiple: `?paymentStatus=&paymentStatus=` - Null: `?paymentStatus=null` **statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself. - Single (partial match, case-insensitive): `?statusLiteral=` - Multiple: `?statusLiteral=&statusLiteral=` - Null: `?statusLiteral=null` **redirectUrl** (`String`): 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. - Single (partial match, case-insensitive): `?redirectUrl=` - Multiple: `?redirectUrl=&redirectUrl=` - Null: `?redirectUrl=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalquotapayments** ```js axios({ method: 'GET', url: '/v1/additionalquotapayments', data: { }, params: { // Filter parameters (see Filter Parameters section above) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_additionalQuotaPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Additionalquotapayment` API This route is used to create a new payment. **Rest Route** The `createAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment` **Rest Request Parameters** The `createAdditionalQuotaPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source additionalQuota object **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/additionalquotapayment** ```js axios({ method: 'POST', url: '/v1/additionalquotapayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Additionalquotapayment` API This route is used to update an existing payment. **Rest Route** The `updateAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` **Rest Request Parameters** The `updateAdditionalQuotaPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **sys_additionalQuotaPaymentId** : This id paremeter is used to select the required data object that will be updated **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'PATCH', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Additionalquotapayment` API This route is used to delete a payment. **Rest Route** The `deleteAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` **Rest Request Parameters** The `deleteAdditionalQuotaPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | **sys_additionalQuotaPaymentId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'DELETE', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Additionalquotapaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getAdditionalQuotaPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/additionalQuotapaymentbyorderid/:orderId` **Rest Request Parameters** The `getAdditionalQuotaPaymentByOrderId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source additionalQuota object. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalQuotapaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/additionalQuotapaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Additionalquotapaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getAdditionalQuotaPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/additionalQuotapaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getAdditionalQuotaPaymentByPaymentId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | **paymentId** : 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. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalQuotapaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/additionalQuotapaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Start Additionalquotapayment` API Start payment for additionalQuota **Rest Route** The `startAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/startadditionalquotapayment/:additionalQuotaId` **Rest Request Parameters** The `startAdditionalQuotaPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **additionalQuotaId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/startadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Refresh Additionalquotapayment` API Refresh payment info for additionalQuota from Stripe **Rest Route** The `refreshAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/refreshadditionalquotapayment/:additionalQuotaId` **Rest Request Parameters** The `refreshAdditionalQuotaPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **additionalQuotaId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to refresh a stripe payment process **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refreshadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/refreshadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Callback Additionalquotapayment` API Refresh payment values by gateway webhook call for additionalQuota **Rest Route** The `callbackAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/callbackadditionalquotapayment` **Rest Request Parameters** The `callbackAdditionalQuotaPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | false | request.body?.["additionalQuotaId"] | **additionalQuotaId** : The order id parameter that will be read from webhook callback params **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/callbackadditionalquotapayment** ```js axios({ method: 'POST', url: '/v1/callbackadditionalquotapayment', data: { additionalQuotaId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Get Paymentcustomerbyuserid` API This route is used to get the payment customer information by user id. **Rest Route** The `getPaymentCustomerByUserId` API REST controller can be triggered via the following route: `/v1/paymentcustomers/:userId` **Rest Request Parameters** The `getPaymentCustomerByUserId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Paymentcustomers` API This route is used to list all payment customers. **Rest Route** The `listPaymentCustomers` API REST controller can be triggered via the following route: `/v1/paymentcustomers` **Rest Request Parameters** **Filter Parameters** The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results: **userId** (`ID`): An ID value to represent the user who is created as a stripe customer - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **customerId** (`String`): 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 - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Paymentcustomermethods` API This route is used to list all payment customer methods. **Rest Route** The `listPaymentCustomerMethods` API REST controller can be triggered via the following route: `/v1/paymentcustomermethods/:userId` **Rest Request Parameters** The `listPaymentCustomerMethods` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who owns the payment method. The parameter is used to query data. **Filter Parameters** The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results: **paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform. - Single (partial match, case-insensitive): `?paymentMethodId=` - Multiple: `?paymentMethodId=&paymentMethodId=` - Null: `?paymentMethodId=null` **customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway. - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer. - Single (partial match, case-insensitive): `?cardHolderName=` - Multiple: `?cardHolderName=&cardHolderName=` - Null: `?cardHolderName=null` **cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries. - Single (partial match, case-insensitive): `?cardHolderZip=` - Multiple: `?cardHolderZip=&cardHolderZip=` - Null: `?cardHolderZip=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **cardInfo** (`Object`): A Json value to store the card details of the payment method. - Single: `?cardInfo=` - Multiple: `?cardInfo=&cardInfo=` - Null: `?cardInfo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## AiCoach Service AdditionalQuota Payment Flow # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - AiCoach Service AdditionalQuota Payment Flow** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend. ## Stripe Payment Flow For AdditionalQuota `AdditionalQuota` is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database. The ID of this data object—referenced as `additionalQuotaId` in the general business logic—will be used as the `orderId` in the payment flow. ## Accessing the service API for the payment flow API The Aifitapp application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders. To access the related APIs, use the base URL of the `aiCoach` service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment. For the `aiCoach` service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/aicoach-api` * **Staging:** `https://appaili-stage.mindbricks.co/aicoach-api` * **Production:** `https://appaili.mindbricks.co/aicoach-api` ## Creating the AdditionalQuota While creating the `additionalQuota` instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of `additionalQuota`). The payment flow begins **after** the object is created. Because of the data object’s **Stripe order settings**, the payment flow is aware of the following fields, references, and their purposes: - `id` (used as `orderId` or `${dataObject.objectName}Id`): The unique identifier of the data object instance at the center of the payment flow. - `orderIdProperty`: The order identifier is read from the `id` property of the data object. - `amountProperty`: The payment amount is read from the `pricePaid` property of the data object. - `currencyProperty`: The payment currency is read from the `currency` property of the data object. - `description`: The payment description is resolved from `runMScript(() => ('additionalquota addition'), {"path":"services[1].dataObjects[11].objectSettings.stripeOrder.configuration.description"})`. - `orderStatusProperty`: `status` is updated automatically by the payment flow using a mapped status value. - `orderStatusUpdateDateProperty`: `statusUpdatedAt` stores the timestamp of the latest payment status update. - `orderOwnerIdProperty`: `userId` is used by the payment flow to verify the order owner and match it with the current user’s ID. - `mapPaymentResultToOrderStatus`: The order status is written to the data object instance using the following mapping. **paymentResultStarted**: `runMScript(() => ('pending'), {"path":"services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted"})` **paymentResultCanceled**: `runMScript(() => ('cancelled'), {"path":"services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled"})` **paymentResultFailed**: `runMScript(() => ('failed'), {"path":"services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed"})` **paymentResultSuccess**: `runMScript(() => ('active'), {"path":"services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess"})` ## Before Payment Flow Starts It is assumed that the frontend provides a **“Pay”** or **“Checkout”** button that initiates the payment flow. The following steps occur after the user clicks this button. Note that an `additionalQuota` instance must already exist to represent the order being paid, with its initial status set. A Stripe payment flow can be implemented in several ways, but the best practice is to use a **PaymentIntent** and manage it jointly from the backend and frontend. A *PaymentIntent* represents the intent to collect payment for a given order (or any payable entity). In the Aifitapp application, the **PaymentIntent** is created in the backend, while the **PaymentMethod** (the user’s stored card information) is created in the frontend. Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference. The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to **add or remove** payment methods. The user must select a Payment Method before starting the payment flow. ### Listing the Payment Methods for the User To list the payment methods of the currently logged-in user, call the following **system API** (unversioned): `GET /payment-methods/list` This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope. ```js const response = await fetch("$serviceUrl/payment-methods/list", { method: "GET", headers: { "Content-Type": "application/json" }, }); ```` Example response: ```json [ { "id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01", "paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8", "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2", "customerId": "cus_TNgWUw5QkmUPLa", "cardHolderName": "John Doe", "cardHolderZip": "34662", "platform": "stripe", "cardInfo": { "brand": "visa", "last4": "4242", "checks": { "cvc_check": "pass", "address_postal_code_check": "pass" }, "funding": "credit", "exp_month": 11, "exp_year": 2033 }, "isActive": true, "createdAt": "2025-11-07T19:16:38.469Z", "updatedAt": "2025-11-07T19:16:38.469Z", "_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2" } ] ``` In each payment method object, the following fields are useful for displaying to the user: ```js for (const method of paymentMethods) { const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow const cardHolderName = method.cardHolderName; // show in list const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date const id = method.id; // internal DB record ID, used for deletion const customerId = method.customerId; // Stripe customer reference } ``` If the list is empty, prompt the user to **add a new payment method**. ### Creating a Payment Method The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled **entirely through Stripe.js** on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse. Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns. To initialize Stripe on the frontend, include your **public key**: ```html ``` ```js const stripe = Stripe("pk_test_51POkqt4.................."); const elements = stripe.elements(); const cardNumberElement = elements.create("cardNumber", { style: { base: { color: "#545454", fontSize: "16px" } }, }); cardNumberElement.mount("#card-number-element"); const cardExpiryElement = elements.create("cardExpiry", { style: { base: { color: "#545454", fontSize: "16px" } }, }); cardExpiryElement.mount("#card-expiry-element"); const cardCvcElement = elements.create("cardCvc", { style: { base: { color: "#545454", fontSize: "16px" } }, }); cardCvcElement.mount("#card-cvc-element"); // Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure). ``` You can dynamically show the card brand while typing: ```js cardNumberElement.on("change", (event) => { const cardBrand = event.brand; const cardNumberDiv = document.getElementById("card-number-element"); cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand); }); ``` Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code. ```js const { paymentMethod, error } = await stripe.createPaymentMethod({ type: "card", card: cardNumberElement, billing_details: { name: cardholderName.value, address: { postal_code: cardholderZip.value }, }, }); ``` When a `paymentMethod` is successfully created, send its ID to your backend to attach it to the logged-in user’s account. Use the **system API** (unversioned): `POST /payment-methods/add` **Example:** ```js const response = await fetch("$serviceUrl/payment-methods/add", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ paymentMethodId: paymentMethod.id }), }); ``` When `addPaymentMethod` is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use. Example response: ```json { "isActive": true, "cardHolderName": "John Doe", "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2", "customerId": "cus_TNgWUw5QkmUPLa", "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP", "platform": "stripe", "cardHolderZip": "34662", "cardInfo": { "brand": "visa", "last4": "4242", "funding": "credit", "exp_month": 11, "exp_year": 2033 }, "id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf", "createdAt": "2025-11-07T20:16:55.451Z", "updatedAt": "2025-11-07T20:16:55.451Z" } ``` You can append this new entry directly to the UI list or refresh the list using the `listPaymentMethods` API. ### Deleting a Payment Method To remove a saved payment method from the current user’s account, call the **system API** (unversioned): `DELETE /payment-methods/delete/:paymentMethodId` **Example:** ```js await fetch( `$serviceUrl/payment-methods/delete/${paymentMethodId}`, { method: "DELETE", headers: { "Content-Type": "application/json" }, } ); ``` ## Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object The payment flow is initiated in the backend through the `startAdditionalQuotaPayment` API. This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend **forces the user to select a payment method** before initiating the payment. The `startAdditionalQuotaPayment` API is a versioned **Business Logic API** and follows the same structure as other business APIs. In the Aifitapp application, the payment flow starts by creating a **Stripe PaymentIntent** and confirming it in a single step within the backend. In a typical (“happy”) path, when the `startAdditionalQuotaPayment` API is called, the response will include a successful or failed PaymentIntent result inside the `paymentResult` object, along with the `additionalQuota` object. However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately. In such cases, control should return to a frontend page to allow the user to finish the process. To enable this, a **`return_url`** must be provided during the PaymentIntent creation step. Although technically optional, it is **strongly recommended** to include a `return_url`. This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction. The `return_url` must be a **frontend URL**. The `paymentUserParams` parameter of the `startAdditionalQuotaPayment` API contains the data necessary to create the Stripe PaymentIntent. Call the API as follows: ```js const response = await fetch( `$serviceUrl/v1/startadditionalQuotapayment/${orderId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ paymentUserParams: { paymentMethodId, return_url: `${yourFrontendReturnUrl}`, }, }), } ); ```` The API response will contain a `paymentResult` object. If an error occurs, it will begin with `{ "result": "ERR" }`. Otherwise, it will include the PaymentIntent information: ```json { "paymentResult": { "success": true, "paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da", "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838", "paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8", "paymentStatus": "succeeded", "paymentIntentInfo": { "paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8", "clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg", "publicKey": "pk_test_51POkqWP5uU", "status": "succeeded" }, "statusLiteral": "success", "amount": 10, "currency": "USD", "description": "Your credit card is charged for babilOrder for 10", "metadata": { "order": "Purchase-Purchase-order", "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838", "checkoutName": "babilOrder" }, "paymentUserParams": { "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP", "return_url": "${yourFrontendReturnUrl}" } } } ``` ### `Start Additionalquotapayment` API Start payment for additionalQuota **Rest Route** The `startAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/startadditionalquotapayment/:additionalQuotaId` **Rest Request Parameters** The `startAdditionalQuotaPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **additionalQuotaId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/startadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ## Analyzing the API Response After calling the `startAdditionalQuotaPayment` API, the most common expected outcome is a confirmed and completed payment. However, several alternate cases should be handled on the frontend. ### System Error Case The API may return a classic service-level error (unrelated to payment). Check the HTTP status code of the response. It should be `200` or `201`. Any `400`, `401`, `403`, or `404` indicates a system error. ```json { "result": "ERR", "status": 404, "message": "Record not found", "date": "2025-11-08T00:57:54.820Z" } ``` **Handle system errors on the payment page** (show a retry option). Do not navigate to the result page. ### Payment Error Case The API performs both database operations and the Stripe payment operation. If the payment fails but the service logic succeeds, the API may still return a `200 OK` status, with the failure recorded in the `paymentResult`. In this case, show an error message and allow the user to retry. ```json { "status": "OK", "statusCode": "200", "additionalQuota": { "id": "19a60f8f-eeff-43a2-9954-58b18839e1da", "status": "failed" }, "paymentResult": { "result": "ERR", "status": 500, "message": "Stripe error message: Your card number is incorrect.", "errCode": "invalid_number", "date": "2025-11-08T00:57:54.820Z" } } ``` **Payment errors should be handled on the payment page** (retry option). Do not go to the result page. --- ### Happy Case When both the service and payment result succeed, this is considered the *happy path*. In this case, use the `additionalQuota` and `paymentResult` objects in the response to display a success message to the user. `amount` and `description` values are included to help you show payment details on the result page. ```json { "status": "OK", "statusCode": "200", "order": { "id": "19a60f8f-eeff-43a2-9954-58b18839e1da", "status": "paid" }, "paymentResult": { "success": true, "paymentStatus": "succeeded", "paymentIntentInfo": { "status": "succeeded" }, "amount": 10, "currency": "USD", "description": "Your credit card is charged for babilOrder for 10" } } ``` To verify success: ```js if (paymentResult.paymentIntentInfo.status === "succeeded") { // Redirect to result page } ``` > Note: A successful result does not trigger fulfillment immediately. > Fulfillment begins only after the Stripe webhook updates the database. > It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page. **Handle the happy case in the result page** by sending the `additionalQuotaId` and the payment intent secret. ```js const orderId = new URLSearchParams(window.location.search).get("orderId"); const url = new URL(`$yourResultPageUrl`, location.origin); url.searchParams.set("orderId", orderId); url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret); setTimeout(() => { window.location.href = url.toString(); }, 600); ``` --- ### Edge Cases Although `startAdditionalQuotaPayment` is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required. You must handle these cases in **both the payment page and the result page**, because some next actions are available immediately, while others occur only after a redirect. If the `paymentIntentInfo.status` equals `"requires_action"`, handle it using Stripe.js as shown below: ```js if (paymentResult.paymentIntentInfo.status === "requires_action") { await runNextAction( paymentResult.paymentIntentInfo.clientSecret, paymentResult.paymentIntentInfo.publicKey ); } ``` Helper function: ```js async function runNextAction(clientSecret, publicKey) { const stripe = Stripe(publicKey); const { error } = await stripe.handleNextAction({ clientSecret }); if (error) { console.log("next_action error:", error); showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500"); throw new Error(error.message); } } ``` After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page. ```js const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret); if (paymentIntent.status === "succeeded") { showToast("Payment successful!", "fa-circle-check text-green-500"); } else if (paymentIntent.status === "processing") { showToast("Payment is processing…", "fa-circle-info text-blue-500"); } else if (paymentIntent.status === "requires_payment_method") { showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500"); } const orderId = new URLSearchParams(window.location.search).get("orderId"); const url = new URL(`$yourResultPageUrl`, location.origin); url.searchParams.set("orderId", orderId); url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret); setTimeout(() => { window.location.href = url.toString(); }, 600); ``` --- ## The Result Page The payment result page should handle the following steps: 1. Read `orderId` and `payment_intent_client_secret` from the query parameters. 2. Retrieve the PaymentIntent from Stripe and check its status. 3. If required, handle any `next_action` and re-fetch the PaymentIntent. 4. If the status is `"succeeded"`, display a clear visual confirmation. 5. Fetch the `additionalQuota` instance from the backend to display any additional order or fulfillment details. Note that paymentIntent status only gives information about the Stripe side. The `additionalQuota` instance in the service should also ve updated to start the fulfillment. In most cases, the `startadditionalQuotaPayment` api updates the status of the order using the response of the paymentIntent confirmation, but as stated above in some cases this update can be done only when the webhook executes. So in teh result page always get the final payment status in the `additionalQuota. To ensure that service i To fetch the `additionalQuota` instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the `additionalQuota` instance. ```js if (additionalQuota.paymentConfirmation == "canceled") { // the payment is canceled, user can be informed that they should try again } if (additionalQuota.paymentConfirmation == "paid") { // service knows that payment is done, user can be informed that fullfillment started } else { // it may be pending, processing // Fetch the object again until a canceled or paid status } ``` --- ## Payment Flow via MCP (AI Chat Integration) The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The `aiCoach` service exposes an `initiatePayment` MCP tool that the AI can call when the user wants to pay for an order. ### How initiatePayment Works in MCP 1. **User asks to pay** — e.g., "I want to pay for my order" 2. **AI calls `initiatePayment`** MCP tool with `orderId` (and `orderType` if multiple order types exist) 3. **Tool validates** the order exists, is payable, and the user is authorized 4. **Tool returns `__frontendAction`** with `type: "payment"` — this is NOT a direct payment execution 5. **Frontend chat UI** renders a `PaymentActionCard` with a "Pay Now" button 6. **User clicks "Pay Now"** — the frontend opens a payment modal with `CheckoutForm` 7. **Standard Stripe flow** proceeds (payment method selection, 3DS handling, etc.) ### Frontend Action Response Format The `initiatePayment` MCP tool returns: ```json { "__frontendAction": { "type": "payment", "orderId": "uuid", "orderType": "additionalQuota", "serviceName": "aiCoach", "amount": 99.99, "currency": "USD", "description": "Order description" }, "message": "Payment is ready. Click the button below to proceed." } ``` ### MCP Client Architecture The frontend communicates with MCP tools through the **MCP BFF** (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides: - **SSE Streaming**: Chat messages stream via `/api/chat/stream` with event types: `start`, `text`, `tool_start`, `tool_executing`, `tool_result`, `error`, `done` - **Tool Result Extraction**: The frontend's `MessageBubble` component inspects tool results for `__frontendAction` fields - **Action Dispatch**: The `ActionCard` component dispatches to type-specific cards (e.g., `PaymentActionCard` for `type: "payment"`) The `PaymentActionCard` component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface. --- ## Subscription Service # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - Subscription Service** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of subscription ## Service Access Subscription service management is handled through service specific base urls. Subscription service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the subscription service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/subscription-api` * **Staging:** `https://appaili-stage.mindbricks.co/subscription-api` * **Production:** `https://appaili.mindbricks.co/subscription-api` ## Scope **Subscription Service Description** Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z Subscription service provides apis and business logic for following data objects in aifitapp application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`pricingConfig` Data Object**: Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record. **`subscription` Data Object**: Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates. **`sys_subscriptionPayment` Data Object**: A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object's checkout config **`sys_paymentCustomer` Data Object**: A payment storage object to store the customer values of the payment platform **`sys_paymentMethod` Data Object**: A payment storage object to store the payment methods of the platform customers ## Subscription Service Frontend Description By The Backend Architect # Subscription Service UX Guide This service manages premium subscriptions. Key UX behaviors: - Users must subscribe to the premium plan before accessing any AI features (training programs, nutrition plans, chatbot). - The subscription pricing is displayed from the pricingConfig endpoint. Show the current price and description to users before they initiate payment. - After successful Stripe payment, the subscription becomes active immediately. Redirect users to the main app experience. - Users can view their subscription status at any time via getMySubscription. - Users can cancel their subscription. After cancellation, inform them that AI features will no longer be accessible. - Admin users manage pricing through API calls. Price changes affect new subscriptions only, not existing ones. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## PricingConfig Data Object Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record. ### PricingConfig Data Object Properties PricingConfig data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `currency` | String | false | Yes | No | Currency code for pricing (e.g., usd). | | `description` | Text | false | No | No | Human-readable description of the subscription plan. | | `price` | Integer | false | Yes | No | Current subscription price in cents (e.g., 999 = $9.99). | | `type` | Enum | false | Yes | No | | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **type**: [subscription, quota] ## Subscription Data Object Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates. ### Subscription Data Object Properties Subscription data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `activatedAt` | Date | false | No | No | Timestamp when the subscription was activated after successful payment. | | `cancelledAt` | Date | false | No | No | Timestamp when the subscription was cancelled by the user. | | `currency` | String | false | Yes | No | Currency code for the payment (e.g., usd). | | `pricePaid` | Integer | false | Yes | No | Amount paid in cents at the time of subscription activation. | | `status` | Enum | false | No | No | Current subscription status managed by Stripe payment flow. | | `statusUpdatedAt` | Date | false | No | No | Timestamp of the last status update, auto-managed by Stripe payment flow. | | `userId` | ID | false | Yes | No | Reference to the user who owns this subscription. | | `paymentConfirmation` | Enum | false | Yes | No | 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, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [pending, active, cancelled, expired, failed] - **paymentConfirmation**: [pending, processing, paid, canceled] ### Relation Properties `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **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. Required: Yes ### Filter Properties `status` `userId` `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. - **status**: Enum has a filter named `status` - **userId**: ID has a filter named `userId` - **paymentConfirmation**: Enum has a filter named `paymentConfirmation` ## Sys_subscriptionPayment Data Object A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object's checkout config ### Sys_subscriptionPayment Data Object Properties Sys_subscriptionPayment data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `ownerId` | ID | false | No | No | An ID value to represent owner user who created the order | | `orderId` | ID | false | Yes | No | an ID value to represent the orderId which is the ID parameter of the source subscription object | | `paymentId` | String | false | Yes | No | 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 | false | Yes | No | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | `statusLiteral` | String | false | Yes | No | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | `redirectUrl` | String | false | No | 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, formula or session bind is set. ### 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. - **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 A payment storage object to store the customer values of the payment platform ### Sys_paymentCustomer Data Object Properties Sys_paymentCustomer data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `userId` | ID | false | No | No | An ID value to represent the user who is created as a stripe customer | | `customerId` | String | false | Yes | No | 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 | false | Yes | No | 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, formula or session bind is set. ### 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. - **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 A payment storage object to store the payment methods of the platform customers ### Sys_paymentMethod Data Object Properties Sys_paymentMethod data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `paymentMethodId` | String | false | Yes | No | A string value to represent the id of the payment method on the payment platform. | | `userId` | ID | false | Yes | No | An ID value to represent the user who owns the payment method | | `customerId` | String | false | Yes | No | A string value to represent the customer id which is generated on the payment gateway. | | `cardHolderName` | String | false | No | No | A string value to represent the name of the card holder. It can be different than the registered customer. | | `cardHolderZip` | String | false | No | No | A string value to represent the zip code of the card holder. It is used for address verification in specific countries. | | `platform` | String | false | Yes | No | 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 | false | Yes | No | 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, formula or session bind is set. ### 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. - **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` ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### PricingConfig Default APIs **Display Label Property:** `description` — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references). | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createPricingConfig` | `/v1/pricingconfigs` | Yes | | Update | `updatePricingConfig` | `/v1/pricingconfigs/:pricingConfigId` | Yes | | Delete | `deletePricingConfig` | `/v1/pricingconfigs/:pricingConfigId` | Yes | | Get | `getPricingConfig` | `/v1/pricingconfigs/:pricingConfigId` | Yes | | List | `listPricingConfigs` | `/v1/pricingconfigs` | Yes | ### Subscription Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createSubscription` | `/v1/subscriptions` | Auto | | Update | `cancelSubscription` | `/v1/subscriptions/:subscriptionId/cancel` | Auto | | Delete | _none_ | - | Auto | | Get | `getSubscription` | `/v1/subscriptions/:subscriptionId` | Yes | | List | `listSubscriptions` | `/v1/subscriptions` | Yes | ### Sys_subscriptionPayment Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createSubscriptionPayment` | `/v1/subscriptionpayment` | Auto | | Update | `updateSubscriptionPayment` | `/v1/subscriptionpayment/:sys_subscriptionPaymentId` | Auto | | Delete | `deleteSubscriptionPayment` | `/v1/subscriptionpayment/:sys_subscriptionPaymentId` | Auto | | Get | `getSubscriptionPayment` | `/v1/subscriptionpayment/:sys_subscriptionPaymentId` | Auto | | List | `listSubscriptionPayments` | `/v1/subscriptionpayments` | Auto | ### Sys_paymentCustomer Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getPaymentCustomerByUserId` | `/v1/paymentcustomers/:userId` | Auto | | List | `listPaymentCustomers` | `/v1/paymentcustomers` | Auto | ### Sys_paymentMethod Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | _none_ | - | Auto | | List | `listPaymentCustomerMethods` | `/v1/paymentcustomermethods/:userId` | Auto | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Cancel Subscription` API Cancel the authenticated user's active subscription. Sets the subscription status to cancelled and records the cancellation timestamp. **API Frontend Description By The Backend Architect** Call this endpoint when the user confirms they want to cancel their subscription. After successful cancellation, inform the user that they will lose access to AI features. The response contains the updated subscription record with status 'cancelled'. **Rest Route** The `cancelSubscription` API REST controller can be triggered via the following route: `/v1/subscriptions/:subscriptionId/cancel` **Rest Request Parameters** The `cancelSubscription` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/subscriptions/:subscriptionId/cancel** ```js axios({ method: 'POST', url: `/v1/subscriptions/${subscriptionId}/cancel`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Check Subscriptionstatus` API Machine-to-machine endpoint for other services to validate if a user has an active subscription. Returns the active subscription record if one exists, or an empty list if not. **Rest Route** The `checkSubscriptionStatus` API REST controller can be triggered via the following route: `/v1/check-status` **Rest Request Parameters** The `checkSubscriptionStatus` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.body?.["userId"] | **userId** : The user ID to check subscription status for. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/check-status** ```js axios({ method: 'POST', url: '/v1/check-status', data: { userId:"ID", }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscriptions", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "subscriptions": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Pricingconfig` API **[Default create API]** — This is the designated default `create` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new pricing configuration record. Admin-only operation for setting up subscription pricing. **Rest Route** The `createPricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs` **Rest Request Parameters** The `createPricingConfig` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | currency | String | true | request.body?.["currency"] | | description | Text | false | request.body?.["description"] | | price | Integer | true | request.body?.["price"] | | type | Enum | true | request.body?.["type"] | **currency** : Currency code for pricing (e.g., usd). **description** : Human-readable description of the subscription plan. **price** : Current subscription price in cents (e.g., 999 = $9.99). **type** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/pricingconfigs** ```js axios({ method: 'POST', url: '/v1/pricingconfigs', data: { currency:"String", description:"Text", price:"Integer", type:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Pricingconfig` API **[Default delete API]** — This is the designated default `delete` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a pricing configuration record. Admin-only operation. **Rest Route** The `deletePricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` **Rest Request Parameters** The `deletePricingConfig` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | **pricingConfigId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'DELETE', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Mysubscription` API Retrieve the currently authenticated user's active subscription. Returns the active subscription if one exists. **API Frontend Description By The Backend Architect** Use this endpoint to check if the current user has an active subscription before allowing access to AI features. If a 404 is returned, the user does not have an active subscription and should be prompted to subscribe. **Rest Route** The `getMySubscription` API REST controller can be triggered via the following route: `/v1/my-subscription` **Rest Request Parameters** The `getMySubscription` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/my-subscription** ```js axios({ method: 'GET', url: '/v1/my-subscription', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Pricingconfig` API **[Default get API]** — This is the designated default `get` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Retrieve a pricing configuration record. Accessible to all authenticated users to view current subscription pricing. **API Frontend Description By The Backend Architect** Use this endpoint to display the current subscription price to users before they initiate payment. **Rest Route** The `getPricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` **Rest Request Parameters** The `getPricingConfig` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | **pricingConfigId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'GET', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Subscription` API **[Default get API]** — This is the designated default `get` API for the `subscription` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Retrieve a subscription record by its ID. Owners can view their own subscriptions; admins can view any. **Rest Route** The `getSubscription` API REST controller can be triggered via the following route: `/v1/subscriptions/:subscriptionId` **Rest Request Parameters** The `getSubscription` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | **subscriptionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptions/:subscriptionId** ```js axios({ method: 'GET', url: `/v1/subscriptions/${subscriptionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Pricingconfigs` API **[Default list API]** — This is the designated default `list` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all pricing configuration records. Accessible to authenticated users. **Rest Route** The `listPricingConfigs` API REST controller can be triggered via the following route: `/v1/pricingconfigs` **Rest Request Parameters** The `listPricingConfigs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/pricingconfigs** ```js axios({ method: 'GET', url: '/v1/pricingconfigs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "pricingConfigs": [ { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Subscriptions` API **[Default list API]** — This is the designated default `list` API for the `subscription` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all subscriptions. Admin-only endpoint for monitoring subscription records. **Rest Route** The `listSubscriptions` API REST controller can be triggered via the following route: `/v1/subscriptions` **Rest Request Parameters** **Filter Parameters** The `listSubscriptions` api supports 3 optional filter parameters for filtering list results: **status** (`Enum`): Current subscription status managed by Stripe payment flow. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this subscription. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptions** ```js axios({ method: 'GET', url: '/v1/subscriptions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscriptions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "subscriptions": [ { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Pricingconfig` API **[Default update API]** — This is the designated default `update` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update the subscription pricing configuration. Admin-only operation for adjusting price, currency, or description without code deployment. **Rest Route** The `updatePricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` **Rest Request Parameters** The `updatePricingConfig` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | | currency | String | false | request.body?.["currency"] | | description | Text | false | request.body?.["description"] | | price | Integer | false | request.body?.["price"] | | type | Enum | false | request.body?.["type"] | **pricingConfigId** : This id paremeter is used to select the required data object that will be updated **currency** : Currency code for pricing (e.g., usd). **description** : Human-readable description of the subscription plan. **price** : Current subscription price in cents (e.g., 999 = $9.99). **type** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'PATCH', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { currency:"String", description:"Text", price:"Integer", type:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Subscription` API **Rest Route** The `createSubscription` API REST controller can be triggered via the following route: `/v1/subscriptions` **Rest Request Parameters** The `createSubscription` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | activatedAt | Date | false | request.body?.["activatedAt"] | | cancelledAt | Date | false | request.body?.["cancelledAt"] | | currency | String | true | request.body?.["currency"] | | pricePaid | Integer | true | request.body?.["pricePaid"] | | statusUpdatedAt | Date | false | request.body?.["statusUpdatedAt"] | **activatedAt** : Timestamp when the subscription was activated after successful payment. **cancelledAt** : Timestamp when the subscription was cancelled by the user. **currency** : Currency code for the payment (e.g., usd). **pricePaid** : Amount paid in cents at the time of subscription activation. **statusUpdatedAt** : Timestamp of the last status update, auto-managed by Stripe payment flow. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/subscriptions** ```js axios({ method: 'POST', url: '/v1/subscriptions', data: { activatedAt:"Date", cancelledAt:"Date", currency:"String", pricePaid:"Integer", statusUpdatedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Do Test` API **Rest Route** The `test` API REST controller can be triggered via the following route: `/v1/test` **Rest Request Parameters** The `test` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/test** ```js axios({ method: 'GET', url: '/v1/test', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "pricingConfigs": [ { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Subscriptionpayment` API This route is used to get the payment information by ID. **Rest Route** The `getSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` **Rest Request Parameters** The `getSubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | **sys_subscriptionPaymentId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'GET', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Subscriptionpayments` API This route is used to list all payments. **Rest Route** The `listSubscriptionPayments` API REST controller can be triggered via the following route: `/v1/subscriptionpayments` **Rest Request Parameters** **Filter Parameters** The `listSubscriptionPayments` api supports 6 optional filter parameters for filtering list results: **ownerId** (`ID`): An ID value to represent owner user who created the order - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source subscription object - Single: `?orderId=` - Multiple: `?orderId=&orderId=` - Null: `?orderId=null` **paymentId** (`String`): 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 - Single (partial match, case-insensitive): `?paymentId=` - Multiple: `?paymentId=&paymentId=` - Null: `?paymentId=null` **paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. - Single (partial match, case-insensitive): `?paymentStatus=` - Multiple: `?paymentStatus=&paymentStatus=` - Null: `?paymentStatus=null` **statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself. - Single (partial match, case-insensitive): `?statusLiteral=` - Multiple: `?statusLiteral=&statusLiteral=` - Null: `?statusLiteral=null` **redirectUrl** (`String`): 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. - Single (partial match, case-insensitive): `?redirectUrl=` - Multiple: `?redirectUrl=&redirectUrl=` - Null: `?redirectUrl=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpayments** ```js axios({ method: 'GET', url: '/v1/subscriptionpayments', data: { }, params: { // Filter parameters (see Filter Parameters section above) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_subscriptionPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Subscriptionpayment` API This route is used to create a new payment. **Rest Route** The `createSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment` **Rest Request Parameters** The `createSubscriptionPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source subscription object **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/subscriptionpayment** ```js axios({ method: 'POST', url: '/v1/subscriptionpayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Subscriptionpayment` API This route is used to update an existing payment. **Rest Route** The `updateSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` **Rest Request Parameters** The `updateSubscriptionPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **sys_subscriptionPaymentId** : This id paremeter is used to select the required data object that will be updated **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'PATCH', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Subscriptionpayment` API This route is used to delete a payment. **Rest Route** The `deleteSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` **Rest Request Parameters** The `deleteSubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | **sys_subscriptionPaymentId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'DELETE', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Subscriptionpaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getSubscriptionPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/subscriptionpaymentbyorderid/:orderId` **Rest Request Parameters** The `getSubscriptionPaymentByOrderId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source subscription object. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/subscriptionpaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Subscriptionpaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getSubscriptionPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/subscriptionpaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getSubscriptionPaymentByPaymentId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | **paymentId** : 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. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/subscriptionpaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Start Subscriptionpayment` API Start payment for subscription **Rest Route** The `startSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/startsubscriptionpayment/:subscriptionId` **Rest Request Parameters** The `startSubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/startsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Refresh Subscriptionpayment` API Refresh payment info for subscription from Stripe **Rest Route** The `refreshSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/refreshsubscriptionpayment/:subscriptionId` **Rest Request Parameters** The `refreshSubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to refresh a stripe payment process **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refreshsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/refreshsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Callback Subscriptionpayment` API Refresh payment values by gateway webhook call for subscription **Rest Route** The `callbackSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/callbacksubscriptionpayment` **Rest Request Parameters** The `callbackSubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | false | request.body?.["subscriptionId"] | **subscriptionId** : The order id parameter that will be read from webhook callback params **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/callbacksubscriptionpayment** ```js axios({ method: 'POST', url: '/v1/callbacksubscriptionpayment', data: { subscriptionId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Get Paymentcustomerbyuserid` API This route is used to get the payment customer information by user id. **Rest Route** The `getPaymentCustomerByUserId` API REST controller can be triggered via the following route: `/v1/paymentcustomers/:userId` **Rest Request Parameters** The `getPaymentCustomerByUserId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Paymentcustomers` API This route is used to list all payment customers. **Rest Route** The `listPaymentCustomers` API REST controller can be triggered via the following route: `/v1/paymentcustomers` **Rest Request Parameters** **Filter Parameters** The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results: **userId** (`ID`): An ID value to represent the user who is created as a stripe customer - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **customerId** (`String`): 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 - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Paymentcustomermethods` API This route is used to list all payment customer methods. **Rest Route** The `listPaymentCustomerMethods` API REST controller can be triggered via the following route: `/v1/paymentcustomermethods/:userId` **Rest Request Parameters** The `listPaymentCustomerMethods` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who owns the payment method. The parameter is used to query data. **Filter Parameters** The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results: **paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform. - Single (partial match, case-insensitive): `?paymentMethodId=` - Multiple: `?paymentMethodId=&paymentMethodId=` - Null: `?paymentMethodId=null` **customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway. - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer. - Single (partial match, case-insensitive): `?cardHolderName=` - Multiple: `?cardHolderName=&cardHolderName=` - Null: `?cardHolderName=null` **cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries. - Single (partial match, case-insensitive): `?cardHolderZip=` - Multiple: `?cardHolderZip=&cardHolderZip=` - Null: `?cardHolderZip=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **cardInfo** (`Object`): A Json value to store the card details of the payment method. - Single: `?cardInfo=` - Multiple: `?cardInfo=&cardInfo=` - Null: `?cardInfo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## Subscription Service Subscription Payment Flow # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - Subscription Service Subscription Payment Flow** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend. ## Stripe Payment Flow For Subscription `Subscription` is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database. The ID of this data object—referenced as `subscriptionId` in the general business logic—will be used as the `orderId` in the payment flow. ## Accessing the service API for the payment flow API The Aifitapp application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders. To access the related APIs, use the base URL of the `subscription` service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment. For the `subscription` service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/subscription-api` * **Staging:** `https://appaili-stage.mindbricks.co/subscription-api` * **Production:** `https://appaili.mindbricks.co/subscription-api` ## Creating the Subscription While creating the `subscription` instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of `subscription`). The payment flow begins **after** the object is created. Because of the data object’s **Stripe order settings**, the payment flow is aware of the following fields, references, and their purposes: - `id` (used as `orderId` or `${dataObject.objectName}Id`): The unique identifier of the data object instance at the center of the payment flow. - `orderIdProperty`: The order identifier is read from the `id` property of the data object. - `amountProperty`: The payment amount is read from the `pricePaid` property of the data object. - `currencyProperty`: The payment currency is read from the `currency` property of the data object. - `description`: The payment description is resolved from `runMScript(() => ('Premium Subscription - AI Fitness & Nutrition Coach'), {"path":"services[2].dataObjects[1].objectSettings.stripeOrder.configuration.description"})`. - `orderStatusProperty`: `status` is updated automatically by the payment flow using a mapped status value. - `orderStatusUpdateDateProperty`: `statusUpdatedAt` stores the timestamp of the latest payment status update. - `orderOwnerIdProperty`: `userId` is used by the payment flow to verify the order owner and match it with the current user’s ID. - `mapPaymentResultToOrderStatus`: The order status is written to the data object instance using the following mapping. **paymentResultStarted**: `runMScript(() => ('pending'), {"path":"services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted"})` **paymentResultCanceled**: `runMScript(() => ('cancelled'), {"path":"services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled"})` **paymentResultFailed**: `runMScript(() => ('failed'), {"path":"services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed"})` **paymentResultSuccess**: `runMScript(() => ('active'), {"path":"services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess"})` ## Before Payment Flow Starts It is assumed that the frontend provides a **“Pay”** or **“Checkout”** button that initiates the payment flow. The following steps occur after the user clicks this button. Note that an `subscription` instance must already exist to represent the order being paid, with its initial status set. A Stripe payment flow can be implemented in several ways, but the best practice is to use a **PaymentIntent** and manage it jointly from the backend and frontend. A *PaymentIntent* represents the intent to collect payment for a given order (or any payable entity). In the Aifitapp application, the **PaymentIntent** is created in the backend, while the **PaymentMethod** (the user’s stored card information) is created in the frontend. Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference. The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to **add or remove** payment methods. The user must select a Payment Method before starting the payment flow. ### Listing the Payment Methods for the User To list the payment methods of the currently logged-in user, call the following **system API** (unversioned): `GET /payment-methods/list` This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope. ```js const response = await fetch("$serviceUrl/payment-methods/list", { method: "GET", headers: { "Content-Type": "application/json" }, }); ```` Example response: ```json [ { "id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01", "paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8", "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2", "customerId": "cus_TNgWUw5QkmUPLa", "cardHolderName": "John Doe", "cardHolderZip": "34662", "platform": "stripe", "cardInfo": { "brand": "visa", "last4": "4242", "checks": { "cvc_check": "pass", "address_postal_code_check": "pass" }, "funding": "credit", "exp_month": 11, "exp_year": 2033 }, "isActive": true, "createdAt": "2025-11-07T19:16:38.469Z", "updatedAt": "2025-11-07T19:16:38.469Z", "_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2" } ] ``` In each payment method object, the following fields are useful for displaying to the user: ```js for (const method of paymentMethods) { const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow const cardHolderName = method.cardHolderName; // show in list const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date const id = method.id; // internal DB record ID, used for deletion const customerId = method.customerId; // Stripe customer reference } ``` If the list is empty, prompt the user to **add a new payment method**. ### Creating a Payment Method The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled **entirely through Stripe.js** on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse. Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns. To initialize Stripe on the frontend, include your **public key**: ```html ``` ```js const stripe = Stripe("pk_test_51POkqt4.................."); const elements = stripe.elements(); const cardNumberElement = elements.create("cardNumber", { style: { base: { color: "#545454", fontSize: "16px" } }, }); cardNumberElement.mount("#card-number-element"); const cardExpiryElement = elements.create("cardExpiry", { style: { base: { color: "#545454", fontSize: "16px" } }, }); cardExpiryElement.mount("#card-expiry-element"); const cardCvcElement = elements.create("cardCvc", { style: { base: { color: "#545454", fontSize: "16px" } }, }); cardCvcElement.mount("#card-cvc-element"); // Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure). ``` You can dynamically show the card brand while typing: ```js cardNumberElement.on("change", (event) => { const cardBrand = event.brand; const cardNumberDiv = document.getElementById("card-number-element"); cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand); }); ``` Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code. ```js const { paymentMethod, error } = await stripe.createPaymentMethod({ type: "card", card: cardNumberElement, billing_details: { name: cardholderName.value, address: { postal_code: cardholderZip.value }, }, }); ``` When a `paymentMethod` is successfully created, send its ID to your backend to attach it to the logged-in user’s account. Use the **system API** (unversioned): `POST /payment-methods/add` **Example:** ```js const response = await fetch("$serviceUrl/payment-methods/add", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ paymentMethodId: paymentMethod.id }), }); ``` When `addPaymentMethod` is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use. Example response: ```json { "isActive": true, "cardHolderName": "John Doe", "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2", "customerId": "cus_TNgWUw5QkmUPLa", "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP", "platform": "stripe", "cardHolderZip": "34662", "cardInfo": { "brand": "visa", "last4": "4242", "funding": "credit", "exp_month": 11, "exp_year": 2033 }, "id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf", "createdAt": "2025-11-07T20:16:55.451Z", "updatedAt": "2025-11-07T20:16:55.451Z" } ``` You can append this new entry directly to the UI list or refresh the list using the `listPaymentMethods` API. ### Deleting a Payment Method To remove a saved payment method from the current user’s account, call the **system API** (unversioned): `DELETE /payment-methods/delete/:paymentMethodId` **Example:** ```js await fetch( `$serviceUrl/payment-methods/delete/${paymentMethodId}`, { method: "DELETE", headers: { "Content-Type": "application/json" }, } ); ``` ## Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object The payment flow is initiated in the backend through the `startSubscriptionPayment` API. This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend **forces the user to select a payment method** before initiating the payment. The `startSubscriptionPayment` API is a versioned **Business Logic API** and follows the same structure as other business APIs. In the Aifitapp application, the payment flow starts by creating a **Stripe PaymentIntent** and confirming it in a single step within the backend. In a typical (“happy”) path, when the `startSubscriptionPayment` API is called, the response will include a successful or failed PaymentIntent result inside the `paymentResult` object, along with the `subscription` object. However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately. In such cases, control should return to a frontend page to allow the user to finish the process. To enable this, a **`return_url`** must be provided during the PaymentIntent creation step. Although technically optional, it is **strongly recommended** to include a `return_url`. This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction. The `return_url` must be a **frontend URL**. The `paymentUserParams` parameter of the `startSubscriptionPayment` API contains the data necessary to create the Stripe PaymentIntent. Call the API as follows: ```js const response = await fetch( `$serviceUrl/v1/startsubscriptionpayment/${orderId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ paymentUserParams: { paymentMethodId, return_url: `${yourFrontendReturnUrl}`, }, }), } ); ```` The API response will contain a `paymentResult` object. If an error occurs, it will begin with `{ "result": "ERR" }`. Otherwise, it will include the PaymentIntent information: ```json { "paymentResult": { "success": true, "paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da", "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838", "paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8", "paymentStatus": "succeeded", "paymentIntentInfo": { "paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8", "clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg", "publicKey": "pk_test_51POkqWP5uU", "status": "succeeded" }, "statusLiteral": "success", "amount": 10, "currency": "USD", "description": "Your credit card is charged for babilOrder for 10", "metadata": { "order": "Purchase-Purchase-order", "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838", "checkoutName": "babilOrder" }, "paymentUserParams": { "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP", "return_url": "${yourFrontendReturnUrl}" } } } ``` ### `Start Subscriptionpayment` API Start payment for subscription **Rest Route** The `startSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/startsubscriptionpayment/:subscriptionId` **Rest Request Parameters** The `startSubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/startsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ## Analyzing the API Response After calling the `startSubscriptionPayment` API, the most common expected outcome is a confirmed and completed payment. However, several alternate cases should be handled on the frontend. ### System Error Case The API may return a classic service-level error (unrelated to payment). Check the HTTP status code of the response. It should be `200` or `201`. Any `400`, `401`, `403`, or `404` indicates a system error. ```json { "result": "ERR", "status": 404, "message": "Record not found", "date": "2025-11-08T00:57:54.820Z" } ``` **Handle system errors on the payment page** (show a retry option). Do not navigate to the result page. ### Payment Error Case The API performs both database operations and the Stripe payment operation. If the payment fails but the service logic succeeds, the API may still return a `200 OK` status, with the failure recorded in the `paymentResult`. In this case, show an error message and allow the user to retry. ```json { "status": "OK", "statusCode": "200", "subscription": { "id": "19a60f8f-eeff-43a2-9954-58b18839e1da", "status": "failed" }, "paymentResult": { "result": "ERR", "status": 500, "message": "Stripe error message: Your card number is incorrect.", "errCode": "invalid_number", "date": "2025-11-08T00:57:54.820Z" } } ``` **Payment errors should be handled on the payment page** (retry option). Do not go to the result page. --- ### Happy Case When both the service and payment result succeed, this is considered the *happy path*. In this case, use the `subscription` and `paymentResult` objects in the response to display a success message to the user. `amount` and `description` values are included to help you show payment details on the result page. ```json { "status": "OK", "statusCode": "200", "order": { "id": "19a60f8f-eeff-43a2-9954-58b18839e1da", "status": "paid" }, "paymentResult": { "success": true, "paymentStatus": "succeeded", "paymentIntentInfo": { "status": "succeeded" }, "amount": 10, "currency": "USD", "description": "Your credit card is charged for babilOrder for 10" } } ``` To verify success: ```js if (paymentResult.paymentIntentInfo.status === "succeeded") { // Redirect to result page } ``` > Note: A successful result does not trigger fulfillment immediately. > Fulfillment begins only after the Stripe webhook updates the database. > It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page. **Handle the happy case in the result page** by sending the `subscriptionId` and the payment intent secret. ```js const orderId = new URLSearchParams(window.location.search).get("orderId"); const url = new URL(`$yourResultPageUrl`, location.origin); url.searchParams.set("orderId", orderId); url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret); setTimeout(() => { window.location.href = url.toString(); }, 600); ``` --- ### Edge Cases Although `startSubscriptionPayment` is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required. You must handle these cases in **both the payment page and the result page**, because some next actions are available immediately, while others occur only after a redirect. If the `paymentIntentInfo.status` equals `"requires_action"`, handle it using Stripe.js as shown below: ```js if (paymentResult.paymentIntentInfo.status === "requires_action") { await runNextAction( paymentResult.paymentIntentInfo.clientSecret, paymentResult.paymentIntentInfo.publicKey ); } ``` Helper function: ```js async function runNextAction(clientSecret, publicKey) { const stripe = Stripe(publicKey); const { error } = await stripe.handleNextAction({ clientSecret }); if (error) { console.log("next_action error:", error); showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500"); throw new Error(error.message); } } ``` After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page. ```js const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret); if (paymentIntent.status === "succeeded") { showToast("Payment successful!", "fa-circle-check text-green-500"); } else if (paymentIntent.status === "processing") { showToast("Payment is processing…", "fa-circle-info text-blue-500"); } else if (paymentIntent.status === "requires_payment_method") { showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500"); } const orderId = new URLSearchParams(window.location.search).get("orderId"); const url = new URL(`$yourResultPageUrl`, location.origin); url.searchParams.set("orderId", orderId); url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret); setTimeout(() => { window.location.href = url.toString(); }, 600); ``` --- ## The Result Page The payment result page should handle the following steps: 1. Read `orderId` and `payment_intent_client_secret` from the query parameters. 2. Retrieve the PaymentIntent from Stripe and check its status. 3. If required, handle any `next_action` and re-fetch the PaymentIntent. 4. If the status is `"succeeded"`, display a clear visual confirmation. 5. Fetch the `subscription` instance from the backend to display any additional order or fulfillment details. Note that paymentIntent status only gives information about the Stripe side. The `subscription` instance in the service should also ve updated to start the fulfillment. In most cases, the `startsubscriptionPayment` api updates the status of the order using the response of the paymentIntent confirmation, but as stated above in some cases this update can be done only when the webhook executes. So in teh result page always get the final payment status in the `subscription. To ensure that service i To fetch the `subscription` instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the `subscription` instance. ```js if (subscription.paymentConfirmation == "canceled") { // the payment is canceled, user can be informed that they should try again } if (subscription.paymentConfirmation == "paid") { // service knows that payment is done, user can be informed that fullfillment started } else { // it may be pending, processing // Fetch the object again until a canceled or paid status } ``` --- ## Payment Flow via MCP (AI Chat Integration) The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The `subscription` service exposes an `initiatePayment` MCP tool that the AI can call when the user wants to pay for an order. ### How initiatePayment Works in MCP 1. **User asks to pay** — e.g., "I want to pay for my order" 2. **AI calls `initiatePayment`** MCP tool with `orderId` (and `orderType` if multiple order types exist) 3. **Tool validates** the order exists, is payable, and the user is authorized 4. **Tool returns `__frontendAction`** with `type: "payment"` — this is NOT a direct payment execution 5. **Frontend chat UI** renders a `PaymentActionCard` with a "Pay Now" button 6. **User clicks "Pay Now"** — the frontend opens a payment modal with `CheckoutForm` 7. **Standard Stripe flow** proceeds (payment method selection, 3DS handling, etc.) ### Frontend Action Response Format The `initiatePayment` MCP tool returns: ```json { "__frontendAction": { "type": "payment", "orderId": "uuid", "orderType": "subscription", "serviceName": "subscription", "amount": 99.99, "currency": "USD", "description": "Order description" }, "message": "Payment is ready. Click the button below to proceed." } ``` ### MCP Client Architecture The frontend communicates with MCP tools through the **MCP BFF** (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides: - **SSE Streaming**: Chat messages stream via `/api/chat/stream` with event types: `start`, `text`, `tool_start`, `tool_executing`, `tool_result`, `error`, `done` - **Tool Result Extraction**: The frontend's `MessageBubble` component inspects tool results for `__frontendAction` fields - **Action Dispatch**: The `ActionCard` component dispatches to type-specific cards (e.g., `PaymentActionCard` for `type: "payment"`) The `PaymentActionCard` component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface. --- ## AgentHub Service # **AIFITAPP** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - AgentHub Service** This document is a part of a REST API guide for the aifitapp project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of agentHub ## Service Access AgentHub service management is handled through service specific base urls. AgentHub service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the agentHub service, the base URLs are: * **Preview:** `https://appaili.prw.mindbricks.com/agenthub-api` * **Staging:** `https://appaili-stage.mindbricks.co/agenthub-api` * **Production:** `https://appaili.mindbricks.co/agenthub-api` ## Scope **AgentHub Service Description** AI Agent Hub AgentHub service provides apis and business logic for following data objects in aifitapp application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`sys_agentOverride` Data Object**: Runtime overrides for design-time agents. Null fields use the design default. **`sys_agentExecution` Data Object**: Agent execution log. Records each agent invocation with input, output, and performance metrics. **`sys_toolCatalog` Data Object**: Cached tool catalog discovered from project services. Refreshed periodically. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## Sys_agentOverride Data Object Runtime overrides for design-time agents. Null fields use the design default. ### Sys_agentOverride Data Object Properties Sys_agentOverride data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `agentName` | String | | Yes | No | Design-time agent name this override applies to. | | `provider` | String | | No | No | Override AI provider (e.g., openai, anthropic). | | `model` | String | | No | No | Override model name. | | `systemPrompt` | Text | | No | No | Override system prompt. | | `temperature` | Double | | No | No | Override temperature (0-2). | | `maxTokens` | Integer | | No | No | Override max tokens. | | `responseFormat` | String | | No | No | Override response format (text/json). | | `selectedTools` | Object | | No | No | Array of tool names from the catalog that this agent can use. | | `guardrails` | Object | | No | No | Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. | | `enabled` | Boolean | | Yes | No | Enable or disable this agent. | | `updatedBy` | ID | | No | No | User who last updated this override. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ## Sys_agentExecution Data Object Agent execution log. Records each agent invocation with input, output, and performance metrics. ### Sys_agentExecution Data Object Properties Sys_agentExecution data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `agentName` | String | | Yes | No | Agent that was executed. | | `agentType` | Enum | | Yes | No | Whether this was a design-time or dynamic agent. | | `source` | Enum | | Yes | No | How the agent was triggered. | | `userId` | ID | | No | No | User who triggered the execution. | | `input` | Object | | No | No | Request input (truncated for large payloads). | | `output` | Object | | No | No | Response output (truncated for large payloads). | | `toolCalls` | Integer | | No | No | Number of tool calls made during execution. | | `tokenUsage` | Object | | No | No | Token usage: { prompt, completion, total }. | | `durationMs` | Integer | | No | No | Execution time in milliseconds. | | `status` | Enum | | Yes | No | Execution status. | | `error` | Text | | No | No | Error message if execution failed. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### 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 additional 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 {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **agentType**: [design, dynamic] - **source**: [rest, sse, kafka, agent] - **status**: [success, error, timeout] ### Filter Properties `agentName` `agentType` `source` `userId` `status` 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. - **agentName**: String has a filter named `agentName` - **agentType**: Enum has a filter named `agentType` - **source**: Enum has a filter named `source` - **userId**: ID has a filter named `userId` - **status**: Enum has a filter named `status` ## Sys_toolCatalog Data Object Cached tool catalog discovered from project services. Refreshed periodically. ### Sys_toolCatalog Data Object Properties Sys_toolCatalog data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `toolName` | String | | Yes | No | Full tool name (e.g., service:apiName). | | `serviceName` | String | | Yes | No | Source service name. | | `description` | Text | | No | No | Tool description. | | `parameters` | Object | | No | No | JSON Schema of tool parameters. | | `lastRefreshed` | Date | | No | No | When this tool was last discovered/refreshed. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Filter Properties `serviceName` 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. - **serviceName**: String has a filter named `serviceName` ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### Sys_agentOverride Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAgentOverride` | `/v1/agentoverride` | Yes | | Update | `updateAgentOverride` | `/v1/agentoverride/:sys_agentOverrideId` | Yes | | Delete | `deleteAgentOverride` | `/v1/agentoverride/:sys_agentOverrideId` | Yes | | Get | `getAgentOverride` | `/v1/agentoverride/:sys_agentOverrideId` | Yes | | List | `listAgentOverrides` | `/v1/agentoverrides` | Yes | ### Sys_agentExecution Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getAgentExecution` | `/v1/agentexecution/:sys_agentExecutionId` | Yes | | List | `listAgentExecutions` | `/v1/agentexecutions` | Yes | ### Sys_toolCatalog Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getToolCatalogEntry` | `/v1/toolcatalogentry/:sys_toolCatalogId` | Yes | | List | `listToolCatalog` | `/v1/toolcatalog` | Yes | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Get Agentoverride` API **[Default get API]** — This is the designated default `get` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `getAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'GET', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentoverrides` API **[Default list API]** — This is the designated default `list` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentOverrides` API REST controller can be triggered via the following route: `/v1/agentoverrides` **Rest Request Parameters** The `listAgentOverrides` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverrides** ```js axios({ method: 'GET', url: '/v1/agentoverrides', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverrides", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentOverrides": [ { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Agentoverride` API **[Default update API]** — This is the designated default `update` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `updateAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `updateAgentOverride` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | | provider | String | | request.body?.["provider"] | | model | String | | request.body?.["model"] | | systemPrompt | Text | | request.body?.["systemPrompt"] | | temperature | Double | | request.body?.["temperature"] | | maxTokens | Integer | | request.body?.["maxTokens"] | | responseFormat | String | | request.body?.["responseFormat"] | | selectedTools | Object | | request.body?.["selectedTools"] | | guardrails | Object | | request.body?.["guardrails"] | | enabled | Boolean | | request.body?.["enabled"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be updated **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **enabled** : Enable or disable this agent. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'PATCH', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", enabled:"Boolean", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Create Agentoverride` API **[Default create API]** — This is the designated default `create` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `createAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride` **Rest Request Parameters** The `createAgentOverride` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | agentName | String | true | request.body?.["agentName"] | | provider | String | false | request.body?.["provider"] | | model | String | false | request.body?.["model"] | | systemPrompt | Text | false | request.body?.["systemPrompt"] | | temperature | Double | false | request.body?.["temperature"] | | maxTokens | Integer | false | request.body?.["maxTokens"] | | responseFormat | String | false | request.body?.["responseFormat"] | | selectedTools | Object | false | request.body?.["selectedTools"] | | guardrails | Object | false | request.body?.["guardrails"] | **agentName** : Design-time agent name this override applies to. **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/agentoverride** ```js axios({ method: 'POST', url: '/v1/agentoverride', data: { agentName:"String", provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Delete Agentoverride` API **[Default delete API]** — This is the designated default `delete` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `deleteAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'DELETE', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `List Toolcatalog` API **[Default list API]** — This is the designated default `list` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listToolCatalog` API REST controller can be triggered via the following route: `/v1/toolcatalog` **Rest Request Parameters** **Filter Parameters** The `listToolCatalog` api supports 1 optional filter parameter for filtering list results: **serviceName** (`String`): Source service name. - Single (partial match, case-insensitive): `?serviceName=` - Multiple: `?serviceName=&serviceName=` - Null: `?serviceName=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalog** ```js axios({ method: 'GET', url: '/v1/toolcatalog', data: { }, params: { // Filter parameters (see Filter Parameters section above) // serviceName: '' // Filter by serviceName } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_toolCatalogs": [ { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Toolcatalogentry` API **[Default get API]** — This is the designated default `get` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getToolCatalogEntry` API REST controller can be triggered via the following route: `/v1/toolcatalogentry/:sys_toolCatalogId` **Rest Request Parameters** The `getToolCatalogEntry` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_toolCatalogId | ID | true | request.params?.["sys_toolCatalogId"] | **sys_toolCatalogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalogentry/:sys_toolCatalogId** ```js axios({ method: 'GET', url: `/v1/toolcatalogentry/${sys_toolCatalogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_toolCatalog": { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentexecutions` API **[Default list API]** — This is the designated default `list` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentExecutions` API REST controller can be triggered via the following route: `/v1/agentexecutions` **Rest Request Parameters** **Filter Parameters** The `listAgentExecutions` api supports 5 optional filter parameters for filtering list results: **agentName** (`String`): Agent that was executed. - Single (partial match, case-insensitive): `?agentName=` - Multiple: `?agentName=&agentName=` - Null: `?agentName=null` **agentType** (`Enum`): Whether this was a design-time or dynamic agent. - Single: `?agentType=` (case-insensitive) - Multiple: `?agentType=&agentType=` - Null: `?agentType=null` **source** (`Enum`): How the agent was triggered. - Single: `?source=` (case-insensitive) - Multiple: `?source=&source=` - Null: `?source=null` **userId** (`ID`): User who triggered the execution. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **status** (`Enum`): Execution status. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecutions** ```js axios({ method: 'GET', url: '/v1/agentexecutions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // agentName: '' // Filter by agentName // agentType: '' // Filter by agentType // source: '' // Filter by source // userId: '' // Filter by userId // status: '' // Filter by status } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecutions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentExecutions": [ { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Agentexecution` API **[Default get API]** — This is the designated default `get` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentExecution` API REST controller can be triggered via the following route: `/v1/agentexecution/:sys_agentExecutionId` **Rest Request Parameters** The `getAgentExecution` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentExecutionId | ID | true | request.params?.["sys_agentExecutionId"] | **sys_agentExecutionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecution/:sys_agentExecutionId** ```js axios({ method: 'GET', url: `/v1/agentexecution/${sys_agentExecutionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecution", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentExecution": { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- # Auth Service ## Service Design Specification # Service Design Specification **Athentication documentation** -Version:**`1.0.6`** ## Scope This document provides a structured architectural overview of the `authentication` module of the project.The `authentication` module of the project is used to generate authentication and authorization specific code for all services but a more specific purpose of the module is also to store all required configuration to generate an automatic user service for the project which is named 'aifitapp-auth-service'. So in this document you will find - The detailed configuration of the authetication module. - The effect of the authetication configuration on the auth (user) service and the detailed structures of the auto-generated user service. - The effect of the authetication configuration on the resource services and the detailed authentication and authorization structures of a resource server. This document has been automatically generated based on the authetication module 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. * **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` This service is accessible via the following environment-specific URLs: * **Preview:** `https://appaili.prw.mindbricks.com/auth-api` * **Staging:** `https://appaili-stage.mindbricks.co/auth-api` * **Production:** `https://appaili.mindbricks.co/auth-api` ## Authentication Essentials Mindbricks provides a comprehensive authentication module that serves as the foundation for user management and security across all services. This module is designed to be flexible, allowing for the generation of authentication and authorization code tailored to project's specific needs. Mindbricks supports multiple authentication strategies, for the first validation of the user, the auth service supports the following authentication strategies: - **Password-based authentication**: Users can log in using a username and password. - **Social login**: Users can authenticate using third-party providers like Google, Facebook, or GitHub. - **Single Sign-On (SSO)**: Users can log in using an SSO provider, allowing for seamless access across multiple applications. - **API Key**: Services can authenticate using API keys for secure communication. Once the user is validated through one of the above strategies, the user is granted a JWT token that can be used to access the protected resources of the service. JWT tokens are generated by the auth service and can be used to access protected resources of the service. The JWT token is open and contains the user's identity and any additional claims required for authorization. The token is signed using a private RSA key, ensuring its integrity and authenticity. Once the JWT token is generated, it can be used to access protected resources of the service. The JWT token is structured as follows: ```json { "keyId": "716a8738ec3d499f84d58bda6ee772ce", "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "sub": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", loginDate: "2023-10-01T12:00:00Z" } ``` Key id for a token represents the private-public key pair used to sign the token. To validate the signature of the token, the public key is used. Any service which will use the JWT token can request a publick ket from the auth service using the following endpoint: ```http GET /publickey?keyId=[keyIdInToken] ``` Mindbricks generated services manages the key rotation automatically, so the public key is always up to date and valid for the JWT tokens generated by the auth service. If you add any manual service to the project which should validate the JWT token, you can use the public key endpoint to get the public key and validate the JWT token signature. The JWT token life cycle is configured in the authentication module of the project. This project uses the following configuration for the JWT token: The token is valid for days after it is issued. And the private key used to sign the token is rotated every days. Note that when a new key is generated to sign the JWT tokens, the old key is still valid for the period of days. So it is recommended to cache the old public keys for the period of days to validate the JWT tokens issued with the old keys. ## The Login Definition The login definition is a crucial part of the authentication module, as it defines how user and tenant model is defined. In this section it is specified how users, user groups, and tenants are defined in the project's data model. These definitions allow Mindbricks to dynamically extract identity and authorization data from project-specific data objects. ### User Settings **Super Admin Identifier**: `admin@admin.com` The login email of the super admin user. This user has full permissions across the project and is not tenant-scoped. When primaryLoginIdentifier is 'email' or 'emailOrMobile', this should be an email address. When it is 'mobile', this should be a mobile number in E.164 format. Super admin user is created automatically when the project is initialized with a roleId of `superAdmin` and a userId of `f7103b85-fcda-4dec-92c6-c336f71fd3a2`. The primary identifier field is populated with `superAdminIdentifier` and marked as verified. When the secondary identifier field is required (`secondaryIdentifierPresence: "required"` or `dualIdentifierRegistration: "both"`), a placeholder value is used (`"noreply@system.local"` for email, `"+10000000000"` for mobile) to satisfy the NOT NULL constraint. **Super Admin User Password**: Super admin user password is defined in this module as well, but masked in this document. To edit it you can use the **User Settings** section of **Login Definition** chapter of the Mindbricks **Authentication Module**. **Username Type**: The type of the username which is stored in the database and written to the session object for information purposes.: -`asFullName`: The username is stored in one property, `fullname`, and represents the full name of the user, which is a combination of first name and last name. -`asNamePair`: The username is stored in two properties, `name` and `surname`, which are combined to form the full name of the user. This project uses the `asFullName` type, so the user name is stored in one property, `fullname`, and represents the full name of the user, which is a combination of first name and last name. **User Groups**: The project does not support user groups, so the auth service will not create any user group related data objects. **Public User Registration**: The project allows public user registration, meaning that users can register themselves without the need for an admin to create an account for them. This is useful for projects that require user self-registration, such as social networks, forums, or any application where users need to create their own accounts. The user registration process is handled by the auth service, which will create a new user data object in the database. The user registration process will create a new user with the `userId` and `roleId` set to `user`, and the user will be able to log in using the username and password they provided during registration. The reigstered user's roleId will be updated later to any other roleId by the super admin or admin users. If any social login is enabled for the project, the user can also sign up using the social login providers. Note that when users register themselves using socila logi, first all the data that can be provided by the social login provider will written to Redis cache with a key called socialCode, and this code will be returned to the api consumer, which can be used to complete the registration process. **Email Verification Required For Login**: The project requires email verification for user login, meaning that users must verify their email address before they can log in. This is useful for projects that require email verification to ensure that users have provided a valid email address, such as social networks, forums, or any application where email verification is required. The email verification process is handled by the auth service, which will send a verification email to the user's email address after they register or change their email address. You can check the email verification details in the REST API documentation of the auth service. **Email 2FA Is Not Required For Login**: The project does not require email-based two-factor authentication (2FA) for user login, meaning that users can log in using only their username and password without providing a second factor of authentication. This is useful for projects that do not require an additional layer of security for user login, such as enterprise applications, internal tools, or any application where email-based 2FA is not required. While the email 2FA is not required, the auth service will still support email 2FA if it is configured in the verification services. You can prefer email 2FA at any time before any action or make it optional which means that users can provide a second factor of authentication if they want to, but it is not required for login. You can check the email 2FA details in the REST API documentation of the auth service. **User Mobile Is Not Active**: The authetication module is not configured to support mobile numbers for users. **User Auto Avatar Script**: Mindbricks stores an avatar property inthe user data model automatically. This project supports also automatic avatar generation for users with the following script configuretion. The auth service will generate an avatar for each user when it is not specified in the registration process. The script is defined in the authentication module and can be edited in the **User Settings** section of **Login Definition** chapter of the Mindbricks **Authentication Module**. The script is executed when a new user is created, and it generates an avatar based on user properties. ```js `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon` ``` ### Tenant Settings This project is not configured to support multi-tenancy, meaning that users and other data are not scoped to a specific tenant. This allows for a single-tenant data management, where all users and other data are shared across the project. ## Verification Services The project supports various verification services that enhance security and user experience. These services are designed to verify user identity through different channels, such as email and mobile, and can be configured to suit the project's needs. Please check the auth service API documentation for more details on how to use these services through the REST API. A verification service is configured with the following settings: -`verificationType`: The type of verification handling, which can be one of the following: -- `byCode`: The verification is handled by entering a code in the frontend. -- `byLink`: The verification is handled by clicking a link in the frontend, which will automatically verify the user through the auth service. -`resendTimeWindow`: The time window in seconds during which the user can request a new verification code or link. -`expireTimeWindow`: The time window in seconds after which the verification code or link will expire and become invalid. ### Password Reset By Email The project supports password reset by email, allowing users to reset their passwords securely through a verification code sent to their registered email address. This service is useful for projects that require users to reset their passwords securely, such as social networks, forums, or any application where password reset is required. The password reset by email process is handled by the auth service, which will send a verification code to the user's email address after they request a password reset. ```json { verificationType: "byCode", resendTimeWindow: 60, expireTimeWindow: 86400 } ``` ### Password Reset By Mobile The project supports password reset by mobile, allowing users to reset their passwords securely through a verification code sent to their registered mobile number. This service is useful for projects that require users to reset their passwords securely, such as social networks, forums, or any application where password reset is required. The password reset by mobile process is handled by the auth service, which will send a verification code to the user's mobile number after they request a password reset. ```json { verificationType: "byCode", resendTimeWindow: 60, expireTimeWindow: 300 } ``` ### Email Verification The project supports email verification, allowing users to verify their email addresses securely through a verification code sent to their registered email address. This service is useful for projects that require users to verify their email addresses securely, such as social networks, forums, or any application where email verification is required. The email verification process is handled by the auth service, which will send a verification code to the user's email address after they register or change their email address. ```json { verificationType: "byCode", resendTimeWindow: 60, expireTimeWindow: 86400 } ``` ### Mobile Verification The project supports mobile verification, allowing users to verify their mobile numbers securely through a verification code sent to their registered mobile number. This service is useful for projects that require users to verify their mobile numbers securely, such as social networks, forums, or any application where mobile verification is required. The mobile verification process is handled by the auth service, which will send a verification code to the user's mobile number after they register or change their mobile number. ```json { verificationType: "byCode", resendTimeWindow: 60, expireTimeWindow: 300 } ``` ### Email 2FA The project supports email-based two-factor authentication (2FA), allowing users to enhance their login security by providing a second factor of authentication, such as a verification code sent to their registered email address. This service is useful for projects that require an additional layer of security for user login, such as social networks, forums, or any application where email-based 2FA is required. The email 2FA process is handled by the auth service, which will send a verification code to the user's email address after they log in. The user must provide the verification code to complete the login process. ```json { verificationType: "byCode", resendTimeWindow: 60, expireTimeWindow: 86400 } ``` ### Mobile 2FA The project supports mobile-based two-factor authentication (2FA), allowing users to enhance their login security by providing a second factor of authentication, such as a verification code sent to their registered mobile number. This service is useful for projects that require an additional layer of security for user login, such as social networks, forums, or any application where mobile-based 2FA is required. The mobile 2FA process is handled by the auth service, which will send a verification code to the user's mobile number after they log in. The user must provide the verification code to complete the login process. ```json { verificationType: "byCode", resendTimeWindow: 60, expireTimeWindow: 300 } ``` ## Access Control (Not Configured) The project does not support any access control mechanisms, meaning that users can access all resources without any restrictions. If you want to add access control mechanisms, you can do so in the **Access Control** chapter of Mindbricks **Authentication Module**. ## Social Logins (Not Configured) The project does not support any social logins, meaning that users cannot log in using their social media accounts. If you want to add social logins, you can do so in the **Social Logins** chapter of Mindbricks **Authentication Module**. ## User Properties `activityLevel` `availableEquipment` `country` `dateOfBirth` `dietaryRestrictions` `fitnessGoal` `height` `sex` `trainingExperience` `weeklyTrainingDays` `weight` The project supports above user properties, allowing for the storage of additional user information beyond the default properties. User properties are defined in the **User Properties** chapter of authentication module and can be edited in the **User Properties** section. These properties can be used to store additional information about users, such as preferences, settings, or any other custom data that is relevant to the project. User properties are stored in the user data object, and they can be accessed and modified through the auth service API. To see a detailed configuretion of the user properties, please check the **User Data Object** docmentation below. ## Auth Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `aifitapp-auth-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 | |-------------|-------------|---------------| | `user` | A data object that stores the user information and handles login settings. | accessPrivate | | `userAvatarsFile` | Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. | accessPublic | ## user Data Object ### Object Overview **Description:** A data object that stores the user information and handles login settings. 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. ### Redis Entity Caching This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `email` | String | Yes | A string value to represent the user's email. | | `password` | String | Yes | A string value to represent the user's password. It will be stored as hashed. | | `fullname` | String | Yes | A string value to represent the fullname of the user | | `avatar` | String | No | The avatar url of the user. A random avatar will be generated if not provided | | `roleId` | String | Yes | A string value to represent the roleId of the user. | | `emailVerified` | Boolean | Yes | A boolean value to represent the email verification status of the user. | | `activityLevel` | Enum | No | User's general daily activity level, used as the TDEE activity multiplier. | | `availableEquipment` | String | No | List of equipment available to the user for training program generation. | | `country` | String | No | User's country of residence, used for regional food suggestions and cuisine preferences. | | `dateOfBirth` | Date | No | User's date of birth, used for age-based calorie and program calculations. | | `dietaryRestrictions` | String | No | List of user dietary restrictions or allergies for meal plan customization. | | `fitnessGoal` | Enum | No | User's primary fitness goal driving program and nutrition recommendations. | | `height` | Float | No | User's height in centimeters, used for BMR and TDEE calculations. | | `sex` | Enum | Yes | User's biological sex, used for BMR calculations and program customization. | | `trainingExperience` | Enum | No | User's training experience level, influencing program complexity and progression rates. | | `weeklyTrainingDays` | Integer | No | Number of days per week the user is available to train, used for program split selection. | | `weight` | Float | No | User's current body weight in kilograms, used for calorie and macro calculations. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `availableEquipment` `dietaryRestrictions` Array properties can hold multiple values and are indicated by the `[]` suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **email**: 'default' - **password**: 'default' - **fullname**: 'default' - **roleId**: user ### 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. - **roleId**: Will be created with value `user` - **emailVerified**: Will be created with value `false` ### Constant Properties `email` 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 `fullname` `avatar` `activityLevel` `availableEquipment` `country` `dateOfBirth` `dietaryRestrictions` `fitnessGoal` `height` `sex` `trainingExperience` `weeklyTrainingDays` `weight` 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. ### Hashed Properties `password` Hashed properties are stored in the database as a hash value, providing an additional layer of security for sensitive data. ### 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. - **activityLevel**: [sedentary, lightTraining, moderate, heavyTraining, athlete] - **fitnessGoal**: [fatLoss, muscleGain, recomposition, strengthMaintenance, generalHealth] - **sex**: [male, female] - **trainingExperience**: [beginner, intermediate, advanced] ### Elastic Search Indexing `email` `fullname` `roleId` `emailVerified` `activityLevel` `availableEquipment` `country` `dateOfBirth` `dietaryRestrictions` `fitnessGoal` `height` `sex` `trainingExperience` `weeklyTrainingDays` `weight` 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 `email` 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 `email` 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. ### Cache Select Properties `email` Cache select properties are used to collect data from Redis entity cache with a different key than the data object id. This allows you to cache data that is not directly related to the data object id, but a frequently used filter. ### Secondary Key Properties `email` 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. ### Filter Properties `email` `fullname` `roleId` `activityLevel` `country` `fitnessGoal` `sex` `trainingExperience` 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. - **email**: String has a filter named `email` - **fullname**: String has a filter named `fullname` - **roleId**: String has a filter named `roleId` - **activityLevel**: Enum has a filter named `activityLevel` - **country**: String has a filter named `country` - **fitnessGoal**: Enum has a filter named `fitnessGoal` - **sex**: Enum has a filter named `sex` - **trainingExperience**: Enum has a filter named `trainingExperience` ## userAvatarsFile Data Object ### Object Overview **Description:** Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. 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:** accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `fileName` | String | Yes | Original file name as uploaded by the client. | | `mimeType` | String | Yes | MIME type of the uploaded file (e.g., image/png, application/pdf). | | `fileSize` | Integer | Yes | File size in bytes. | | `accessKey` | String | Yes | 12-character random key for shareable access. Auto-generated on upload. | | `ownerId` | ID | No | ID of the user who uploaded the file (from session). | | `fileData` | Blob | Yes | Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB. | | `metadata` | Object | No | Optional JSON metadata for the file (tags, alt text, etc.). | | `userId` | ID | No | Reference to the owner user record. | * 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. - **fileName**: 'default' - **mimeType**: 'default' - **fileSize**: 0 - **accessKey**: 'default' - **fileData**: Buffer.alloc(0) ### Constant Properties `fileName` `mimeType` `fileSize` `accessKey` `ownerId` `fileData` `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 `fileName` `mimeType` `fileSize` `accessKey` `ownerId` `fileData` `metadata` `userId` 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 `fileName` `mimeType` `fileSize` `ownerId` `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 `fileName` `mimeType` `accessKey` `ownerId` `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. ### Unique Properties `accessKey` 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. ### 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 `mimeType` `ownerId` `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. - **mimeType**: String has a filter named `mimeType` - **ownerId**: ID has a filter named `ownerId` - **userId**: ID has a filter named `userId` --- ## REST API GUIDE # REST API GUIDE ## aifitapp-auth-service **Version:** `1.0.6` Authentication service for the project ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Auth Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Auth Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Auth Service via HTTP requests for purposes such as creating, updating, deleting and querying Auth objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the Auth Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the Auth service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | appaili-access-token| | Cookie | appaili-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the Auth service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Auth service. This service is configured to listen for HTTP requests on port `3011`, 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` This service is accessible via the following environment-specific URLs: * **Preview:** `https://appaili.prw.mindbricks.com/auth-api` * **Staging:** `https://appaili-stage.mindbricks.co/auth-api` * **Production:** `https://appaili.mindbricks.co/auth-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the Auth service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `Auth` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Auth` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `Auth` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources Auth service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### User resource *Resource Definition* : A data object that stores the user information and handles login settings. *User Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **email** | String | | | * A string value to represent the user's email.* | | **password** | String | | | * A string value to represent the user's password. It will be stored as hashed.* | | **fullname** | String | | | *A string value to represent the fullname of the user* | | **avatar** | String | | | *The avatar url of the user. A random avatar will be generated if not provided* | | **roleId** | String | | | *A string value to represent the roleId of the user.* | | **emailVerified** | Boolean | | | *A boolean value to represent the email verification status of the user.* | | **activityLevel** | Enum | | | *User's general daily activity level, used as the TDEE activity multiplier.* | | **availableEquipment** | String | | | *List of equipment available to the user for training program generation.* | | **country** | String | | | *User's country of residence, used for regional food suggestions and cuisine preferences.* | | **dateOfBirth** | Date | | | *User's date of birth, used for age-based calorie and program calculations.* | | **dietaryRestrictions** | String | | | *List of user dietary restrictions or allergies for meal plan customization.* | | **fitnessGoal** | Enum | | | *User's primary fitness goal driving program and nutrition recommendations.* | | **height** | Float | | | *User's height in centimeters, used for BMR and TDEE calculations.* | | **sex** | Enum | | | *User's biological sex, used for BMR calculations and program customization.* | | **trainingExperience** | Enum | | | *User's training experience level, influencing program complexity and progression rates.* | | **weeklyTrainingDays** | Integer | | | *Number of days per week the user is available to train, used for program split selection.* | | **weight** | Float | | | *User's current body weight in kilograms, used for calorie and macro calculations.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### activityLevel Enum Property *Property Definition* : User's general daily activity level, used as the TDEE activity multiplier.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **sedentary** | `"sedentary""` | 0 | | **lightTraining** | `"lightTraining""` | 1 | | **moderate** | `"moderate""` | 2 | | **heavyTraining** | `"heavyTraining""` | 3 | | **athlete** | `"athlete""` | 4 | ##### fitnessGoal Enum Property *Property Definition* : User's primary fitness goal driving program and nutrition recommendations.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **fatLoss** | `"fatLoss""` | 0 | | **muscleGain** | `"muscleGain""` | 1 | | **recomposition** | `"recomposition""` | 2 | | **strengthMaintenance** | `"strengthMaintenance""` | 3 | | **generalHealth** | `"generalHealth""` | 4 | ##### sex Enum Property *Property Definition* : User's biological sex, used for BMR calculations and program customization.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **male** | `"male""` | 0 | | **female** | `"female""` | 1 | ##### trainingExperience Enum Property *Property Definition* : User's training experience level, influencing program complexity and progression rates.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **beginner** | `"beginner""` | 0 | | **intermediate** | `"intermediate""` | 1 | | **advanced** | `"advanced""` | 2 | ### UserAvatarsFile resource *Resource Definition* : Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. *UserAvatarsFile Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **fileName** | String | | | *Original file name as uploaded by the client.* | | **mimeType** | String | | | *MIME type of the uploaded file (e.g., image/png, application/pdf).* | | **fileSize** | Integer | | | *File size in bytes.* | | **accessKey** | String | | | *12-character random key for shareable access. Auto-generated on upload.* | | **ownerId** | ID | | | *ID of the user who uploaded the file (from session).* | | **fileData** | Blob | | | *Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.* | | **metadata** | Object | | | *Optional JSON metadata for the file (tags, alt text, etc.).* | | **userId** | ID | | | *Reference to the owner user record.* | ## Business Api ### `Get User` API This api is used by admin roles or the users themselves to get the user profile information. **Rest Route** The `getUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `getUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users/:userId** ```js axios({ method: 'GET', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update User` API This route is used by admins to update user profiles. **Rest Route** The `updateUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `updateUser` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | false | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/users/:userId** ```js axios({ method: 'PATCH', url: `/v1/users/${userId}`, data: { fullname:"String", avatar:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Profile` API This route is used by users to update their profiles. **Rest Route** The `updateProfile` API REST controller can be triggered via the following route: `/v1/profile/:userId` **Rest Request Parameters** The `updateProfile` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | false | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/profile/:userId** ```js axios({ method: 'PATCH', url: `/v1/profile/${userId}`, data: { fullname:"String", avatar:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create User` API This api is used by admin roles to create a new user manually from admin panels **Rest Route** The `createUser` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** The `createUser` api has got 15 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | email | String | true | request.body?.["email"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | true | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **email** : A string value to represent the user's email. **password** : A string value to represent the user's password. It will be stored as hashed. **fullname** : A string value to represent the fullname of the user **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/users** ```js axios({ method: 'POST', url: '/v1/users', data: { avatar:"String", email:"String", password:"String", fullname:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete User` API This api is used by admins to delete user profiles. **Rest Route** The `deleteUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `deleteUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/users/:userId** ```js axios({ method: 'DELETE', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Archive Profile` API This api is used by users to archive their profiles. **Rest Route** The `archiveProfile` API REST controller can be triggered via the following route: `/v1/archiveprofile/:userId` **Rest Request Parameters** The `archiveProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/archiveprofile/:userId** ```js axios({ method: 'DELETE', url: `/v1/archiveprofile/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Users` API The list of users is filtered by the tenantId. **Rest Route** The `listUsers` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** **Filter Parameters** The `listUsers` api supports 8 optional filter parameters for filtering list results: **email** (`String`): A string value to represent the user's email. - Single (partial match, case-insensitive): `?email=` - Multiple: `?email=&email=` - Null: `?email=null` **fullname** (`String`): A string value to represent the fullname of the user - Single (partial match, case-insensitive): `?fullname=` - Multiple: `?fullname=&fullname=` - Null: `?fullname=null` **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **activityLevel** (`Enum`): User's general daily activity level, used as the TDEE activity multiplier. - Single: `?activityLevel=` (case-insensitive) - Multiple: `?activityLevel=&activityLevel=` - Null: `?activityLevel=null` **country** (`String`): User's country of residence, used for regional food suggestions and cuisine preferences. - Single (partial match, case-insensitive): `?country=` - Multiple: `?country=&country=` - Null: `?country=null` **fitnessGoal** (`Enum`): User's primary fitness goal driving program and nutrition recommendations. - Single: `?fitnessGoal=` (case-insensitive) - Multiple: `?fitnessGoal=&fitnessGoal=` - Null: `?fitnessGoal=null` **sex** (`Enum`): User's biological sex, used for BMR calculations and program customization. - Single: `?sex=` (case-insensitive) - Multiple: `?sex=&sex=` - Null: `?sex=null` **trainingExperience** (`Enum`): User's training experience level, influencing program complexity and progression rates. - Single: `?trainingExperience=` (case-insensitive) - Multiple: `?trainingExperience=&trainingExperience=` - Null: `?trainingExperience=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users** ```js axios({ method: 'GET', url: '/v1/users', data: { }, params: { // Filter parameters (see Filter Parameters section above) // email: '' // Filter by email // fullname: '' // Filter by fullname // roleId: '' // Filter by roleId // activityLevel: '' // Filter by activityLevel // country: '' // Filter by country // fitnessGoal: '' // Filter by fitnessGoal // sex: '' // Filter by sex // trainingExperience: '' // Filter by trainingExperience } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Search Users` API The list of users is filtered by the tenantId. **Rest Route** The `searchUsers` API REST controller can be triggered via the following route: `/v1/searchusers` **Rest Request Parameters** The `searchUsers` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | keyword | String | true | request.query?.["keyword"] | **keyword** : **Filter Parameters** The `searchUsers` api supports 6 optional filter parameters for filtering list results: **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **activityLevel** (`Enum`): User's general daily activity level, used as the TDEE activity multiplier. - Single: `?activityLevel=` (case-insensitive) - Multiple: `?activityLevel=&activityLevel=` - Null: `?activityLevel=null` **country** (`String`): User's country of residence, used for regional food suggestions and cuisine preferences. - Single (partial match, case-insensitive): `?country=` - Multiple: `?country=&country=` - Null: `?country=null` **fitnessGoal** (`Enum`): User's primary fitness goal driving program and nutrition recommendations. - Single: `?fitnessGoal=` (case-insensitive) - Multiple: `?fitnessGoal=&fitnessGoal=` - Null: `?fitnessGoal=null` **sex** (`Enum`): User's biological sex, used for BMR calculations and program customization. - Single: `?sex=` (case-insensitive) - Multiple: `?sex=&sex=` - Null: `?sex=null` **trainingExperience** (`Enum`): User's training experience level, influencing program complexity and progression rates. - Single: `?trainingExperience=` (case-insensitive) - Multiple: `?trainingExperience=&trainingExperience=` - Null: `?trainingExperience=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/searchusers** ```js axios({ method: 'GET', url: '/v1/searchusers', data: { }, params: { keyword:'"String"', // Filter parameters (see Filter Parameters section above) // roleId: '' // Filter by roleId // activityLevel: '' // Filter by activityLevel // country: '' // Filter by country // fitnessGoal: '' // Filter by fitnessGoal // sex: '' // Filter by sex // trainingExperience: '' // Filter by trainingExperience } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Userrole` API This route is used by admin roles to update the user role.The default role is user when a user is registered. A user's role can be updated by superAdmin or admin **Rest Route** The `updateUserRole` API REST controller can be triggered via the following route: `/v1/userrole/:userId` **Rest Request Parameters** The `updateUserRole` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | roleId | String | true | request.body?.["roleId"] | **userId** : This id paremeter is used to select the required data object that will be updated **roleId** : The new roleId of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userrole/:userId** ```js axios({ method: 'PATCH', url: `/v1/userrole/${userId}`, data: { roleId:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpassword` API This route is used to update the password of users in the profile page by users themselves **Rest Route** The `updateUserPassword` API REST controller can be triggered via the following route: `/v1/userpassword/:userId` **Rest Request Parameters** The `updateUserPassword` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | oldPassword | String | true | request.body?.["oldPassword"] | | newPassword | String | true | request.body?.["newPassword"] | **userId** : This id paremeter is used to select the required data object that will be updated **oldPassword** : The old password of the user that will be overridden bu the new one. Send for double check. **newPassword** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpassword/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpassword/${userId}`, data: { oldPassword:"String", newPassword:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpasswordbyadmin` API This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords **Rest Route** The `updateUserPasswordByAdmin` API REST controller can be triggered via the following route: `/v1/userpasswordbyadmin/:userId` **Rest Request Parameters** The `updateUserPasswordByAdmin` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | password | String | true | request.body?.["password"] | **userId** : This id paremeter is used to select the required data object that will be updated **password** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpasswordbyadmin/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpasswordbyadmin/${userId}`, data: { password:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Briefuser` API This route is used by public to get simple user profile information. **Rest Route** The `getBriefUser` API REST controller can be triggered via the following route: `/v1/briefuser/:userId` **Rest Request Parameters** The `getBriefUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/briefuser/:userId** ```js axios({ method: 'GET', url: `/v1/briefuser/${userId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "isActive": true } } ``` ### `Stream Test` API Test API for iterator action streaming via SSE. **Rest Route** The `streamTest` API REST controller can be triggered via the following route: `/v1/streamtest/:userId` **Rest Request Parameters** The `streamTest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/streamtest/:userId** ```js axios({ method: 'GET', url: `/v1/streamtest/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Register User` API This api is used by public users to register themselves **Rest Route** The `registerUser` API REST controller can be triggered via the following route: `/v1/registeruser` **Rest Request Parameters** The `registerUser` api has got 15 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | email | String | true | request.body?.["email"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | true | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **password** : The password defined by the the user that is being registered. **fullname** : The fullname defined by the the user that is being registered. **email** : The email defined by the the user that is being registered. **activityLevel** : User's general daily activity level, used as the TDEE activity multiplier. **availableEquipment** : List of equipment available to the user for training program generation. **country** : User's country of residence, used for regional food suggestions and cuisine preferences. **dateOfBirth** : User's date of birth, used for age-based calorie and program calculations. **dietaryRestrictions** : List of user dietary restrictions or allergies for meal plan customization. **fitnessGoal** : User's primary fitness goal driving program and nutrition recommendations. **height** : User's height in centimeters, used for BMR and TDEE calculations. **sex** : User's biological sex, used for BMR calculations and program customization. **trainingExperience** : User's training experience level, influencing program complexity and progression rates. **weeklyTrainingDays** : Number of days per week the user is available to train, used for program split selection. **weight** : User's current body weight in kilograms, used for calorie and macro calculations. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/registeruser** ```js axios({ method: 'POST', url: '/v1/registeruser', data: { avatar:"String", password:"String", fullname:"String", email:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Useravatarsfile` API **[Default get API]** — This is the designated default `get` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getUserAvatarsFile` API REST controller can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` **Rest Request Parameters** The `getUserAvatarsFile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | **userAvatarsFileId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'GET', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Useravatarsfiles` API **[Default list API]** — This is the designated default `list` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listUserAvatarsFiles` API REST controller can be triggered via the following route: `/v1/useravatarsfiles` **Rest Request Parameters** **Filter Parameters** The `listUserAvatarsFiles` api supports 3 optional filter parameters for filtering list results: **mimeType** (`String`): MIME type of the uploaded file (e.g., image/png, application/pdf). - Single (partial match, case-insensitive): `?mimeType=` - Multiple: `?mimeType=&mimeType=` - Null: `?mimeType=null` **ownerId** (`ID`): ID of the user who uploaded the file (from session). - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **userId** (`ID`): Reference to the owner user record. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles** ```js axios({ method: 'GET', url: '/v1/useravatarsfiles', data: { }, params: { // Filter parameters (see Filter Parameters section above) // mimeType: '' // Filter by mimeType // ownerId: '' // Filter by ownerId // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userAvatarsFiles": [ { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Delete Useravatarsfile` API **[Default delete API]** — This is the designated default `delete` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteUserAvatarsFile` API REST controller can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` **Rest Request Parameters** The `deleteUserAvatarsFile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | **userAvatarsFileId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'DELETE', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### Authentication Specific Routes ### Route: login *Route Definition*: Handles the login process by verifying user credentials and generating an authenticated session. *Route Type*: login *Access Routes*: - `GET /login`: Returns the HTML login page (not a frontend module, typically used in browser-based contexts for test purpose to make sending POST /login easier). - `POST /login`: Accepts credentials, verifies the user, creates a session, and returns a JWT access token. #### Parameters | Parameter | Type | Required | Population | |-------------|----------|----------|-----------------------------| | username | String | Yes | `request.body.username` | | password | String | Yes | `request.body.password` | #### Notes - This route accepts login credentials and creates an authenticated session if credentials are valid. - On success, the response will: - Set a cookie named `projectname-access-token[-tenantCodename]` with the JWT token. - Include the token in the response headers under the same name. - Return the full `session` object in the JSON body. - Note that `username` parameter should have the email of the user as value. You can also send an `email` parameter instead of `username` parameter. If both sent only `username` parameter will be read. ```js // Sample POST /login call axios.post("/login", { username: "user@example.com", password: "securePassword" }); ```` **Success Response** Returns the authenticated session object with a status code `200 OK`. A secure HTTP-only cookie and an access token header are included in the response. ```json { "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", ... } ```` **Error Responses** * **401 Unauthorized:** Invalid username or password. * **403 Forbidden:** Login attempt rejected due to pending email/mobile verification or 2FA requirements. * **400 Bad Request:** Missing credentials in the request. ### Route: logout *Route Definition*: Logs the user out by terminating the current session and clearing the access token. *Route Type*: logout *Access Route*: `POST /logout` #### Parameters This route does not require any parameters in the body or query. #### Behavior - Invalidates the current session on the server (if stored). - Clears the access token cookie (`projectname-access-token[-tenantCodename]`) from the client. - Responds with a 200 status and a simple confirmation object. ```js // Sample POST /logout call axios.post("/logout", {}, { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Notes** * This route is public, meaning it can be called without a session or token. * If the session is active, the server will clear associated session state and cookies. * The logout behavior may vary slightly depending on whether you're using cookie-based or header-based token management. **Error Responses** 00200 OK:** Always returned, regardless of whether a session existed. Logout is treated as idempotent. ### Route: publickey *Route Definition*: Returns the public RSA key used to verify JWT access tokens issued by the auth service. *Route Type*: publicKeyFetch *Access Route*: `GET /publickey` #### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|--------------------| | keyId | String | No | `request.query.keyId` | - `keyId` is optional. If provided, retrieves the public key corresponding to the specific `keyId`. If omitted, retrieves the current active public key (`global.currentKeyId`). #### Behavior - Reads the requested RSA public key file from the server filesystem. - If the key exists, returns it along with its `keyId`. - If the key does not exist, returns a 404 error. ```js // Sample GET /publickey call axios.get("/publickey", { params: { keyId: "currentKeyIdOptional" } }); ```` **Success Response** Returns the active public key and its associated keyId. ```json { "keyId": "a1b2c3d4", "keyData": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhki...\n-----END PUBLIC KEY-----" } ```` **Error Responses** **404 Not Found:** Public key file could not be found on the server. ### Token Key Management Mindbricks uses RSA key pairs to sign and verify JWT access tokens securely. While the auth service signs each token with a private key, other services within the system — or external clients — need the corresponding **public key** to verify the authenticity and integrity of received tokens. The `/publickey` endpoint allows services and clients to dynamically fetch the currently active public key, ensuring that token verification remains secure even if key rotation is performed. > **Note**: > The `/publickey` route is not intended for direct frontend (browser) consumption. > Instead, it is primarily used by trusted backend services, APIs, or middleware systems that need to independently verify access tokens issued by the auth service — without making verification-dependent API calls to the auth service itself. Accessing the public key is crucial for validating user sessions efficiently and maintaining a decentralized trust model across your platform. ### Route: relogin *Route Definition*: Performs a silent login by verifying the current access token, refreshing the session, and returning a new access token along with updated user information. *Route Type*: sessionRefresh *Access Route*: `GET /relogin` #### Parameters This route does **not** require any request parameters. #### Behavior - Validates the access token associated with the request. - If the token is valid: - Re-authenticates the user using the session's user ID. - Fetches the most up-to-date user information from the database. - Generates a new session object with a **new session ID** and **new access token**. - If the token is invalid or missing, returns a 401 Unauthorized error. ```js // Example call to refresh session axios.get("/relogin", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns a new session object, refreshed from database data. ```json { "sessionId": "new-session-uuid", "userId": "user-uuid", "email": "user@example.com", "roleId": "admin", "accessToken": "new-jwt-token", ... } ```` **Error Responses** * **401 Unauthorized**: Token is missing, invalid, or session cannot be re-established. ```json { "status": "ERR", "message": "Cannot relogin" } ```` **Notes** - The `/relogin` route is commonly used for **silent login flows**, especially after page reloads or token-based auto-login mechanisms. - It triggers internal logic (`req.userAuthUpdate = true`) to signal that the session should be re-initialized and repopulated. - It is not a simple session lookup — it performs a fresh authentication pass using the session's user context. - The refreshed session ensures any updates to user profile, roles, or permissions are immediately reflected. > **Tip:** > This route is ideal when you want to **rebuild a user's session** in the frontend without requiring them to manually log in again. ## Verification Services — Email Verification Email verification is a two-step flow that ensures a user's email address is verified and trusted by the system. All verification services, including email verification, are located under the `/verification-services` base path. ### When is Email Verification Triggered? - After user registration, if `emailVerificationRequiredForLogin` is active. - During a separate user action to verify or update email addresses. - When login fails with `EmailVerificationNeeded` and frontend initiates verification. ### Email Verification Flow 1. **Frontend calls `/verification-services/email-verification/start`** with the user's email address. - Mindbricks checks if the email is already verified. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's email or returned in the response (only in development environments for easier testing). 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/email-verification/complete`** with the `email` and the received `secretCode`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s `emailVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/email-verification/start` **Purpose** Starts the email verification process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------| | email | String | Yes | The email address to verify | ```json { "email": "user@example.com" } ```` #### Success Response Secret code details (in development environment). Confirms that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` > ⚠️ In production, the secret code is only sent via email, not exposed in the API response. #### Error Responses - `400 Bad Request`: Email already verified. - `403 Forbidden`: Sending a code too frequently (anti-spam). --- ### POST `/verification-services/email-verification/complete` **Purpose** Completes the email verification by validating the secret code. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------| | email | String | Yes | The user email being verified | | secretCode | String | Yes | The secret code received via email | ```json { "email": "user@example.com", "secretCode": "123456" } ```` #### Success Response Returns confirmation that the email has been verified. ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ```` #### Error Responses - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes ### Resend Throttling You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds). ### Expiration Handling Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day). ### One Code Per Session Only one active verification session per user is allowed at a time. > 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps. ## Verification Services — Mobile Verification Mobile verification is a two-step flow that ensures a user's mobile number is verified and trusted by the system. All verification services, including mobile verification, are located under the `/verification-services` base path. ### When is Mobile Verification Triggered? - After user registration, if `mobileVerificationRequiredForLogin` is active. - During a separate user action to verify or update mobile numbers. - When login fails with `MobileVerificationNeeded` and frontend initiates verification. ### Mobile Verification Flow 1. **Frontend calls `/verification-services/mobile-verification/start`** with the user's email address (used to locate the user). - Mindbricks checks if the mobile number is already verified. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's mobile via SMS or returned in the response (only in development environments for easier testing). 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/mobile-verification/complete`** with the `email` and the received `secretCode`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s `mobileVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/mobile-verification/start` **Purpose**: Starts the mobile verification process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address associated with the mobile number to verify | ```json { "email": "user@example.com" } ```` **Success Response** Secret code details (in development environment). Confirms that the verification step has been started. ```json { "userId": "user-uuid", "mobile": "+15551234567", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the secret code is only sent via SMS, not exposed in the API response. **Error Responses** - 400 Bad Request: Mobile already verified. - 403 Forbidden: Sending a code too frequently (anti-spam). --- ### POST `/verification-services/mobile-verification/complete` **Purpose**: Completes the mobile verification by validating the secret code. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|------------------------------------| | email | String | Yes | The user's email being verified | | secretCode | String | Yes | The secret code received via SMS | ```json { "email": "user@example.com", "secretCode": "123456" } ```` **Success Response** Returns confirmation that the mobile number has been verified. ```json { "userId": "user-uuid", "mobile": "+15551234567", "isVerified": true } ```` **Error Responses** 403 Forbidden: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes **Resend Throttling**: You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds). **Expiration Handling**: Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day). **One Code Per Session**: Only one active verification session per user is allowed at a time. 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps. ## Verification Services — Email 2FA Verification Email 2FA (Two-Factor Authentication) provides an additional layer of security by requiring users to confirm their identity using a secret code sent to their email address. This process is used in login flows or sensitive actions that need extra verification. All verification services, including 2FA, are located under the `/verification-services` base path. ### When is Email 2FA Triggered? - During login flows where `sessionNeedsEmail2FA` is `true` - When the backend enforces two-factor authentication for a sensitive operation ### Email 2FA Flow 1. **Frontend calls `/verification-services/email-2factor-verification/start`** with the user's id, session id, client info, and reason. - Mindbricks identifies the user and checks if a cooldown period applies. - A new secret code is generated and stored, linked to the current session ID. - The code is sent via email or returned in development environments. 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/email-2factor-verification/complete`** with the `userId`, `sessionId`, and the `secretCode`. - Mindbricks verifies the code, validates the session, and updates the session to remove the 2FA requirement. --- ## API Endpoints ### POST `/verification-services/email-2factor-verification/start` **Purpose**: Starts the email-based 2FA process by generating and sending a verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The current session ID | | client | String | No | Optional client tag or context | | reason | String | No | Optional reason for triggering 2FA | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "client": "login-page", "reason": "Login requires email 2FA" } ```` #### Success Response ```json { "sessionId": "session-uuid", "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 300, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the `secretCode` is only sent via email, not exposed in the API response. #### Error Responses - **403 Forbidden**: Sending a code too frequently (anti-spam) - **401 Unauthorized**: User session not found --- ### POST `/verification-services/email-2factor-verification/complete` **Purpose**: Completes the email 2FA process by validating the secret code and session. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|--------------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The session ID the code is tied to | | secretCode | String | Yes | The secret code received via email | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "secretCode": "123456" } ```` #### Success Response Returns an updated session with 2FA disabled: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "sessionNeedsEmail2FA": false, ... } ```` #### Error Responses - **403 Forbidden**: - Secret code mismatch - Secret code expired - Verification step not found --- ### Important Behavioral Notes - **One Code Per Session**: Only one active code can be issued per session. - **Resend Throttling**: Code requests are throttled based on `resendTimeWindow` (e.g., 60 seconds). - **Expiration**: Codes expire after `expireTimeWindow` (e.g., 5 minutes). - 💡 Mindbricks manages session cache, spam control, expiration tracking, and event notifications for all 2FA steps. ## Verification Services — Mobile 2FA Verification Mobile 2FA (Two-Factor Authentication) is a security mechanism that adds an extra layer of authentication using a user's verified mobile number. All verification services, including mobile 2FA, are accessible under the `/verification-services` base path. ### When is Mobile 2FA Triggered? - During login or critical actions requiring step-up authentication. - When the session has a flag `sessionNeedsMobile2FA = true`. - When login or session verification fails with `MobileVerificationNeeded`, indicating 2FA is required. ### Mobile 2FA Verification Flow 1. **Frontend calls `/verification-services/mobile-2factor-verification/start`** with the user's id, session id, client info, and reason. - Mindbricks finds the user by id. - Verifies that the user has a verified mobile number. - A secret code is generated and cached against the session. - The code is sent to the user's verified mobile number or returned in the response (only in development environments). 2. **User receives the code and enters it in the frontend app.** 3. **Frontend calls `/verification-services/mobile-2factor-verification/complete`** with the `userId`, `sessionId`, and `secretCode`. - Mindbricks validates the code for expiration and correctness. - If valid, the session flag `sessionNeedsMobile2FA` is cleared. - A refreshed session object is returned. --- ## API Endpoints ### POST `/verification-services/mobile-2factor-verification/start` **Purpose**: Initiates mobile-based 2FA by generating and sending a secret code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The current session ID | | client | String | No | Optional client tag or context | | reason | String | No | Optional reason for triggering 2FA | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "client": "login-page", "reason": "Login requires mobile 2FA" } ```` **Success Response** Returns the generated code (only in development), expiration info, and metadata. ```json { "userId": "user-uuid", "sessionId": "session-uuid", "mobile": "+15551234567", "secretCode": "654321", "expireTime": 300, "date": "2024-04-29T11:00:00.000Z" } ```` ⚠️ In production environments, the secret code is not included in the response and is instead delivered via SMS. **Error Responses** - 403 Forbidden: Mobile number not verified. - 403 Forbidden: Code resend attempted before cooldown period (`resendTimeWindow`). - 401 Unauthorized: Email not recognized or session invalid. --- ### POST `/verification-services/mobile-2factor-verification/complete` **Purpose**: Completes mobile 2FA verification by validating the secret code and updating the session. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------| | userId | String | Yes | ID of the user | | sessionId | String | Yes | ID of the session | | secretCode | String | Yes | The 6-digit code received via SMS | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "secretCode": "654321" } ```` **Success Response** Returns the updated session with `sessionNeedsMobile2FA: false`. ```json { "sessionId": "session-uuid", "userId": "user-uuid", "sessionNeedsMobile2FA": false, "accessToken": "jwt-token", "expiresIn": 86400 } ```` **Error Responses** - 403 Forbidden: Code mismatch or expired. - 403 Forbidden: No ongoing verification found. - 401 Unauthorized: Session does not exist or is invalid. --- ### Behavioral Notes - **Rate Limiting**: A user can only request a new mobile 2FA code after the cooldown period (`resendTimeWindow`, e.g., 60 seconds). - **Expiration**: Mobile 2FA codes expire after the configured time (`expireTimeWindow`, e.g., 5 minutes). - **Session Integrity**: Verification status is tied to the session; incorrect sessionId will invalidate the attempt. 💡 Mindbricks handles session integrity, rate limiting, and secure code delivery to ensure a robust mobile 2FA process. ## Verification Services — Password Reset by Email Password Reset by Email enables a user to securely reset their password using a secret code sent to their registered email address. All verification services, including password reset by email, are located under the `/verification-services` base path. ### When is Password Reset by Email Triggered? - When a user requests to reset their password by providing their email address. - This service is typically exposed on a “Forgot Password?” flow in the frontend. ### Password Reset Flow 1. **Frontend calls `/verification-services/password-reset-by-email/start`** with the user's email. - Mindbricks checks if the user exists and if the email is registered. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's email, or returned in the response (in development environments only for testing). 2. **User receives the code and enters it into the frontend along with the new password.** 3. **Frontend calls `/verification-services/password-reset-by-email/complete`** with the `email`, the `secretCode`, and the new `password`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s password is reset, their `emailVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/password-reset-by-email/start` **Purpose**: Starts the password reset process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address of the user | ```json { "email": "user@example.com" } ```` **Success Response** Returns secret code details (only in development environment) and confirmation that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the secret code is only sent via email and not exposed in the API response. **Error Responses** - `401 NotAuthenticated`: Email address not found or not associated with a user. - `403 Forbidden`: Sending a code too frequently (spam prevention). --- ### POST `/verification-services/password-reset-by-email/complete` **Purpose**: Completes the password reset process by validating the secret code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|----------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via email | | password | String | Yes | The new password the user wants to set | ```json { "email": "user@example.com", "secretCode": "123456", "password": "newSecurePassword123" } ```` **Success Response** ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ```` **Error Responses** - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes ### Resend Throttling: A new verification code can only be requested after a cooldown period (configured via `resendTimeWindow`, e.g., 60 seconds). ### Expiration Handling: Verification codes automatically expire after a predefined period (`expireTimeWindow`, e.g., 1 day). ### Session & Event Handling: Mindbricks manages: - Spam prevention - Code caching per user - Expiration logic - Verification start/complete events ## Verification Services — Password Reset by Mobile Password reset by mobile provides users with a secure mechanism to reset their password using a verification code sent via SMS to their registered mobile number. All verification services, including password reset by mobile, are located under the `/verification-services` base path. ### When is Password Reset by Mobile Triggered? - When a user forgets their password and selects the mobile reset option. - When a user explicitly initiates password recovery via mobile on the login or help screen. ### Password Reset by Mobile Flow 1. **Frontend calls `/verification-services/password-reset-by-mobile/start`** with the user's mobile number or associated identifier. - Mindbricks checks if a user with the given mobile exists. - A secret code is generated and stored in the cache for that user. - The code is sent to the user's mobile (or returned in development environments for testing). 2. **User receives the code via SMS and enters it into the frontend app.** 3. **Frontend calls `/verification-services/password-reset-by-mobile/complete`** with the user's `email`, the `secretCode`, and the new `password`. - Mindbricks validates the secret code and its expiration. - If valid, it updates the user's password and returns a success response. --- ## API Endpoints ### POST `/verification-services/password-reset-by-mobile/start` **Purpose**: Initiates the mobile-based password reset by sending a verification code to the user's mobile. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|------------------------------| | mobile | String | Yes | The mobile number to verify | ```json { "mobile": "+905551234567" } ```` ### Success Response Returns the verification context (code returned only in development): ```json { "userId": "user-uuid", "mobile": "+905551234567", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the `secretCode` is not included in the response and is only sent via SMS. ### Error Responses - **400 Bad Request**: Mobile already verified - **403 Forbidden**: Rate-limited (code already sent recently) - **404 Not Found**: User with provided mobile not found --- ### POST `/verification-services/password-reset-by-mobile/complete` **Purpose**: Finalizes the password reset process by validating the received verification code and updating the user’s password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via SMS | | password | String | Yes | The new password to assign | ```json { "email": "user@example.com", "secretCode": "123456", "password": "NewSecurePassword123!" } ```` ### Success Response ```json { "userId": "user-uuid", "mobile": "+905551234567", "isVerified": true } ```` --- ### Important Behavioral Notes - **Throttling**: Codes can only be resent after a delay defined by `resendTimeWindow` (e.g., 60 seconds). - **Expiration**: Codes expire after the `expireTimeWindow` (e.g., 1 day). - **One Active Session**: Only one active password reset session is allowed per user at a time. - **Session-less**: This flow does not require an active session — it works for unauthenticated users. 💡 Mindbricks handles spam protection, session caching, and event-based logging (for both start and complete operations) as part of the verification service base class. ## Verification Method Types ### 🧾 For byCode Verifications This verification type requires the user to manually enter a 6-digit code. **Frontend Action**: Display a secure input page where the user can enter the code they received via email or SMS. After collecting the code and any required metadata (such as `userId` or `sessionId`), make a `POST` request to the corresponding `/complete` endpoint. --- ### 🔗 For byLink Verifications This verification type uses a clickable link embedded in an email (or SMS message). **Frontend Action**: The link points to a `GET` page in your frontend that parses `userId` and `code` from the query string and sends them to the backend via a `POST` request to the corresponding `/complete` endpoint. This enables one-click verification without requiring the user to type in a code. ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- ## EVENT GUIDE # EVENT GUIDE ## aifitapp-auth-service Authentication service for the project ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. # Documentation Scope Welcome to the official documentation for the `Auth` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `Auth` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `Auth` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `Auth` objects. **Overview** This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples. # Authentication and Authorization Access to the `Auth` service's events is facilitated through the project's Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server. Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide. # Database Events Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic. Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service's scope, ensuring data consistency and syncronization across services. For example, while a business operation such as "approve membership" might generate a high-level business event like `membership-approved`, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as `dbevent-member-updated` and `dbevent-user-updated`, reflecting the granular changes at the database level. Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes. ## DbEvent user-created **Event topic**: `appaili-auth-service-dbevent-user-created` This event is triggered upon the creation of a `user` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent user-updated **Event topic**: `appaili-auth-service-dbevent-user-updated` Activation of this event follows the update of a `user` data object. The payload contains the updated information under the `user` attribute, along with the original data prior to update, labeled as `old_user` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_user:{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, user:{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent user-deleted **Event topic**: `appaili-auth-service-dbevent-user-deleted` This event announces the deletion of a `user` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent userAvatarsFile-created **Event topic**: `appaili-auth-service-dbevent-useravatarsfile-created` This event is triggered upon the creation of a `userAvatarsFile` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent userAvatarsFile-updated **Event topic**: `appaili-auth-service-dbevent-useravatarsfile-updated` Activation of this event follows the update of a `userAvatarsFile` data object. The payload contains the updated information under the `userAvatarsFile` attribute, along with the original data prior to update, labeled as `old_userAvatarsFile` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_userAvatarsFile:{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, userAvatarsFile:{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent userAvatarsFile-deleted **Event topic**: `appaili-auth-service-dbevent-useravatarsfile-deleted` This event announces the deletion of a `userAvatarsFile` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false} ``` # ElasticSearch Index Events Within the `Auth` service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects. These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries. It's noteworthy that some services may augment another service's index by appending to the entity’s `extends` object. In such scenarios, an `*-extended` event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID. This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications. ## Index Event user-created **Event topic**: `elastic-index-aifitapp_user-created` **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event user-updated **Event topic**: `elastic-index-aifitapp_user-created` **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event user-deleted **Event topic**: `elastic-index-aifitapp_user-deleted` **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event user-extended **Event topic**: `elastic-index-aifitapp_user-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event user-retrived **Event topic** : `appaili-auth-service-user-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-updated **Event topic** : `appaili-auth-service-user-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-updated **Event topic** : `appaili-auth-service-profile-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-created **Event topic** : `appaili-auth-service-user-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-deleted **Event topic** : `appaili-auth-service-user-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-archived **Event topic** : `appaili-auth-service-profile-archived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event users-listed **Event topic** : `appaili-auth-service-users-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `users` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`users`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event users-searched **Event topic** : `appaili-auth-service-users-searched` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `users` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`users`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event userrole-updated **Event topic** : `appaili-auth-service-userrole-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpassword-updated **Event topic** : `appaili-auth-service-userpassword-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpasswordbyadmin-updated **Event topic** : `appaili-auth-service-userpasswordbyadmin-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event briefuser-retrived **Event topic** : `appaili-auth-service-briefuser-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"isActive":true}} ``` ## Route Event user-registered **Event topic** : `appaili-auth-service-user-registered` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event useravatarsfile-retrived **Event topic** : `appaili-auth-service-useravatarsfile-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `userAvatarsFile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`userAvatarsFile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event useravatarsfiles-listed **Event topic** : `appaili-auth-service-useravatarsfiles-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `userAvatarsFiles` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`userAvatarsFiles`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","userAvatarsFiles":[{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event useravatarsfile-deleted **Event topic** : `appaili-auth-service-useravatarsfile-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `userAvatarsFile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`userAvatarsFile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Index Event useravatarsfile-created **Event topic**: `elastic-index-aifitapp_useravatarsfile-created` **Event payload**: ```json {"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event useravatarsfile-updated **Event topic**: `elastic-index-aifitapp_useravatarsfile-created` **Event payload**: ```json {"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event useravatarsfile-deleted **Event topic**: `elastic-index-aifitapp_useravatarsfile-deleted` **Event payload**: ```json {"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event useravatarsfile-extended **Event topic**: `elastic-index-aifitapp_useravatarsfile-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event user-retrived **Event topic** : `appaili-auth-service-user-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-updated **Event topic** : `appaili-auth-service-user-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-updated **Event topic** : `appaili-auth-service-profile-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-created **Event topic** : `appaili-auth-service-user-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-deleted **Event topic** : `appaili-auth-service-user-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-archived **Event topic** : `appaili-auth-service-profile-archived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event users-listed **Event topic** : `appaili-auth-service-users-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `users` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`users`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event users-searched **Event topic** : `appaili-auth-service-users-searched` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `users` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`users`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event userrole-updated **Event topic** : `appaili-auth-service-userrole-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpassword-updated **Event topic** : `appaili-auth-service-userpassword-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpasswordbyadmin-updated **Event topic** : `appaili-auth-service-userpasswordbyadmin-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event briefuser-retrived **Event topic** : `appaili-auth-service-briefuser-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"isActive":true}} ``` ## Route Event user-registered **Event topic** : `appaili-auth-service-user-registered` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `user` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`user`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","activityLevel":"Enum","activityLevel_idx":"Integer","availableEquipment":"String","country":"String","dateOfBirth":"Date","dietaryRestrictions":"String","fitnessGoal":"Enum","fitnessGoal_idx":"Integer","height":"Float","sex":"Enum","sex_idx":"Integer","trainingExperience":"Enum","trainingExperience_idx":"Integer","weeklyTrainingDays":"Integer","weight":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event useravatarsfile-retrived **Event topic** : `appaili-auth-service-useravatarsfile-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `userAvatarsFile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`userAvatarsFile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event useravatarsfiles-listed **Event topic** : `appaili-auth-service-useravatarsfiles-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `userAvatarsFiles` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`userAvatarsFiles`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","userAvatarsFiles":[{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event useravatarsfile-deleted **Event topic** : `appaili-auth-service-useravatarsfile-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `userAvatarsFile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`userAvatarsFile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` # Copyright All sources, documents and other digital materials are copyright of . # About Us For more information please visit our website: . . . --- ## Data Objects ### Service Design Specification - Object Design for user # Service Design Specification - Object Design for user **aifitapp-auth-service** documentation ## Document Overview This document outlines the object design for the `user` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## user Data Object ### Object Overview **Description:** A data object that stores the user information and handles login settings. 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. ### Redis Entity Caching This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `email` | String | Yes | A string value to represent the user's email. | | `password` | String | Yes | A string value to represent the user's password. It will be stored as hashed. | | `fullname` | String | Yes | A string value to represent the fullname of the user | | `avatar` | String | No | The avatar url of the user. A random avatar will be generated if not provided | | `roleId` | String | Yes | A string value to represent the roleId of the user. | | `emailVerified` | Boolean | Yes | A boolean value to represent the email verification status of the user. | | `activityLevel` | Enum | No | User's general daily activity level, used as the TDEE activity multiplier. | | `availableEquipment` | String | No | List of equipment available to the user for training program generation. | | `country` | String | No | User's country of residence, used for regional food suggestions and cuisine preferences. | | `dateOfBirth` | Date | No | User's date of birth, used for age-based calorie and program calculations. | | `dietaryRestrictions` | String | No | List of user dietary restrictions or allergies for meal plan customization. | | `fitnessGoal` | Enum | No | User's primary fitness goal driving program and nutrition recommendations. | | `height` | Float | No | User's height in centimeters, used for BMR and TDEE calculations. | | `sex` | Enum | Yes | User's biological sex, used for BMR calculations and program customization. | | `trainingExperience` | Enum | No | User's training experience level, influencing program complexity and progression rates. | | `weeklyTrainingDays` | Integer | No | Number of days per week the user is available to train, used for program split selection. | | `weight` | Float | No | User's current body weight in kilograms, used for calorie and macro calculations. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `availableEquipment` `dietaryRestrictions` Array properties can hold multiple values and are indicated by the `[]` suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **email**: 'default' - **password**: 'default' - **fullname**: 'default' - **roleId**: user ### 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. - **roleId**: Will be created with value `user` - **emailVerified**: Will be created with value `false` ### Constant Properties `email` 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 `fullname` `avatar` `activityLevel` `availableEquipment` `country` `dateOfBirth` `dietaryRestrictions` `fitnessGoal` `height` `sex` `trainingExperience` `weeklyTrainingDays` `weight` 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. ### Hashed Properties `password` Hashed properties are stored in the database as a hash value, providing an additional layer of security for sensitive data. ### 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. - **activityLevel**: [sedentary, lightTraining, moderate, heavyTraining, athlete] - **fitnessGoal**: [fatLoss, muscleGain, recomposition, strengthMaintenance, generalHealth] - **sex**: [male, female] - **trainingExperience**: [beginner, intermediate, advanced] ### Elastic Search Indexing `email` `fullname` `roleId` `emailVerified` `activityLevel` `availableEquipment` `country` `dateOfBirth` `dietaryRestrictions` `fitnessGoal` `height` `sex` `trainingExperience` `weeklyTrainingDays` `weight` 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 `email` 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 `email` 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. ### Cache Select Properties `email` Cache select properties are used to collect data from Redis entity cache with a different key than the data object id. This allows you to cache data that is not directly related to the data object id, but a frequently used filter. ### Secondary Key Properties `email` 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. ### Filter Properties `email` `fullname` `roleId` `activityLevel` `country` `fitnessGoal` `sex` `trainingExperience` 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. - **email**: String has a filter named `email` - **fullname**: String has a filter named `fullname` - **roleId**: String has a filter named `roleId` - **activityLevel**: Enum has a filter named `activityLevel` - **country**: String has a filter named `country` - **fitnessGoal**: Enum has a filter named `fitnessGoal` - **sex**: Enum has a filter named `sex` - **trainingExperience**: Enum has a filter named `trainingExperience` --- ### Service Design Specification - Object Design for userAvatarsFile # Service Design Specification - Object Design for userAvatarsFile **aifitapp-auth-service** documentation ## Document Overview This document outlines the object design for the `userAvatarsFile` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## userAvatarsFile Data Object ### Object Overview **Description:** Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. 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:** accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `fileName` | String | Yes | Original file name as uploaded by the client. | | `mimeType` | String | Yes | MIME type of the uploaded file (e.g., image/png, application/pdf). | | `fileSize` | Integer | Yes | File size in bytes. | | `accessKey` | String | Yes | 12-character random key for shareable access. Auto-generated on upload. | | `ownerId` | ID | No | ID of the user who uploaded the file (from session). | | `fileData` | Blob | Yes | Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB. | | `metadata` | Object | No | Optional JSON metadata for the file (tags, alt text, etc.). | | `userId` | ID | No | Reference to the owner user record. | * 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. - **fileName**: 'default' - **mimeType**: 'default' - **fileSize**: 0 - **accessKey**: 'default' - **fileData**: Buffer.alloc(0) ### Constant Properties `fileName` `mimeType` `fileSize` `accessKey` `ownerId` `fileData` `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 `fileName` `mimeType` `fileSize` `accessKey` `ownerId` `fileData` `metadata` `userId` 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 `fileName` `mimeType` `fileSize` `ownerId` `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 `fileName` `mimeType` `accessKey` `ownerId` `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. ### Unique Properties `accessKey` 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. ### 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 `mimeType` `ownerId` `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. - **mimeType**: String has a filter named `mimeType` - **ownerId**: ID has a filter named `ownerId` - **userId**: ID has a filter named `userId` --- ## Business APIs ### Business API Design Specification - `Get User` # Business API Design Specification - `Get User` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getUser` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getUser` Business API is designed to handle a `get` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This api is used by admin roles or the users themselves to get the user profile information. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `user-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getUser` Business API includes a REST controller that can be triggered via the following route: `/v1/users/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `getUser` Business API includes a gRPC controller that can be triggered via the following function: `getUser()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getUser` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getUser` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getUser` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin, admin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[0].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Action : emitUserLoaded **Action Type**: `EmitSseEventAction` ```js class Api { async emitUserLoaded() { const eventData = runMScript( () => ({ userId: this.user?.id, fullname: this.user?.fullname, email: this.user?.email, }), { path: "services[0].businessLogic[0].actions.emitSseEventActions[0].data", }, ); await this.emitProgress( "userLoaded", typeof eventData === "string" ? eventData : "", typeof eventData === "object" ? eventData : {}, ); } } ``` --- ### [9] Action : simulateEnrichment **Action Type**: `FunctionCallAction` ```js class Api { async simulateEnrichment() { try { return await runMScript( () => (async () => await new Promise((r) => setTimeout(r, 50)))(), { path: "services[0].businessLogic[0].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction simulateEnrichment:", err); throw err; } } } ``` --- ### [10] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [11] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [12] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [13] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getUser` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/users/:userId** ```js axios({ method: 'GET', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update User` # Business API Design Specification - `Update User` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateUser` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateUser` Business API is designed to handle a `update` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used by admins to update user profiles. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `user-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateUser` Business API includes a REST controller that can be triggered via the following route: `/v1/users/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `updateUser` Business API includes a gRPC controller that can be triggered via the following function: `updateUser()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateUser` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateUser` Business API has 14 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `fullname` | `String` | `No` | `-` | `body` | `fullname` | | **Description:** | A string value to represent the fullname of the user | | | | | | | | | | | | | `avatar` | `String` | `No` | `-` | `body` | `avatar` | | **Description:** | The avatar url of the user. A random avatar will be generated if not provided | | | | | | | | | | | | | `activityLevel` | `Enum` | `No` | `-` | `body` | `activityLevel` | | **Description:** | User's general daily activity level, used as the TDEE activity multiplier. | | | | | | | | | | | | | `availableEquipment` | `String` | `No` | `-` | `body` | `availableEquipment` | | **Description:** | List of equipment available to the user for training program generation. | | | | | | | | | | | | | `country` | `String` | `No` | `-` | `body` | `country` | | **Description:** | User's country of residence, used for regional food suggestions and cuisine preferences. | | | | | | | | | | | | | `dateOfBirth` | `Date` | `No` | `-` | `body` | `dateOfBirth` | | **Description:** | User's date of birth, used for age-based calorie and program calculations. | | | | | | | | | | | | | `dietaryRestrictions` | `String` | `No` | `-` | `body` | `dietaryRestrictions` | | **Description:** | List of user dietary restrictions or allergies for meal plan customization. | | | | | | | | | | | | | `fitnessGoal` | `Enum` | `No` | `-` | `body` | `fitnessGoal` | | **Description:** | User's primary fitness goal driving program and nutrition recommendations. | | | | | | | | | | | | | `height` | `Float` | `No` | `-` | `body` | `height` | | **Description:** | User's height in centimeters, used for BMR and TDEE calculations. | | | | | | | | | | | | | `sex` | `Enum` | `No` | `-` | `body` | `sex` | | **Description:** | User's biological sex, used for BMR calculations and program customization. | | | | | | | | | | | | | `trainingExperience` | `Enum` | `No` | `-` | `body` | `trainingExperience` | | **Description:** | User's training experience level, influencing program complexity and progression rates. | | | | | | | | | | | | | `weeklyTrainingDays` | `Integer` | `No` | `-` | `body` | `weeklyTrainingDays` | | **Description:** | Number of days per week the user is available to train, used for program split selection. | | | | | | | | | | | | | `weight` | `Float` | `No` | `-` | `body` | `weight` | | **Description:** | User's current body weight in kilograms, used for calorie and macro calculations. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateUser` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `saasAdmin`, `admin`, `tenantOwner`, `tenantAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[1].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { fullname: this.fullname, avatar: this.avatar, activityLevel: this.activityLevel, availableEquipment: this.availableEquipment ? this.availableEquipment : ( this.availableEquipment_remove ? sequelize.fn('array_remove', sequelize.col('availableEquipment'), this.availableEquipment_remove) : (this.availableEquipment_append ? sequelize.fn('array_append', sequelize.col('availableEquipment'), this.availableEquipment_append) : undefined)) , country: this.country, dateOfBirth: this.dateOfBirth, dietaryRestrictions: this.dietaryRestrictions ? this.dietaryRestrictions : ( this.dietaryRestrictions_remove ? sequelize.fn('array_remove', sequelize.col('dietaryRestrictions'), this.dietaryRestrictions_remove) : (this.dietaryRestrictions_append ? sequelize.fn('array_append', sequelize.col('dietaryRestrictions'), this.dietaryRestrictions_append) : undefined)) , fitnessGoal: this.fitnessGoal, height: this.height, sex: this.sex, trainingExperience: this.trainingExperience, weeklyTrainingDays: this.weeklyTrainingDays, weight: this.weight, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Action : setRolesOrder **Action Type**: `CreateObjectAction` Sets the hiyerarchy of the roles to check user permissions on other users ```js class Api { async setRolesOrder() { // Construct base object const obj = {}; // Merge dynamic object Object.assign( obj, runMScript( () => ({ superAdmin: 20, saasAdmin: 19, admin: 18, tenantOwner: 17, tenantAdmin: 16, saasUser: 15, tenantUser: 14, user: 13, }), { path: "services[0].businessLogic[1].actions.createObjectActions[0].mergeObject", }, ), ); return obj; } } ``` --- ### [9] Action : protectHigherRole **Action Type**: `ValidationAction` Prevents the update of a higher or equal user role if not themselves ```js class Api { async protectHigherRole() { const isValid = runMScript( () => (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0), { path: "services[0].businessLogic[1].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError("AHigherUserRoleCantBeChanged"); } return isValid; } } ``` --- ### [10] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [11] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [12] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [13] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [14] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [15] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateUser` api has got 14 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | false | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/users/:userId** ```js axios({ method: 'PATCH', url: `/v1/users/${userId}`, data: { fullname:"String", avatar:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Profile` # Business API Design Specification - `Update Profile` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateProfile` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateProfile` Business API is designed to handle a `update` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used by users to update their profiles. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `profile-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateProfile` Business API includes a REST controller that can be triggered via the following route: `/v1/profile/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `updateProfile` Business API includes a gRPC controller that can be triggered via the following function: `updateProfile()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateProfile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateProfile` Business API has 14 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `fullname` | `String` | `No` | `-` | `body` | `fullname` | | **Description:** | A string value to represent the fullname of the user | | | | | | | | | | | | | `avatar` | `String` | `No` | `-` | `body` | `avatar` | | **Description:** | The avatar url of the user. A random avatar will be generated if not provided | | | | | | | | | | | | | `activityLevel` | `Enum` | `No` | `-` | `body` | `activityLevel` | | **Description:** | User's general daily activity level, used as the TDEE activity multiplier. | | | | | | | | | | | | | `availableEquipment` | `String` | `No` | `-` | `body` | `availableEquipment` | | **Description:** | List of equipment available to the user for training program generation. | | | | | | | | | | | | | `country` | `String` | `No` | `-` | `body` | `country` | | **Description:** | User's country of residence, used for regional food suggestions and cuisine preferences. | | | | | | | | | | | | | `dateOfBirth` | `Date` | `No` | `-` | `body` | `dateOfBirth` | | **Description:** | User's date of birth, used for age-based calorie and program calculations. | | | | | | | | | | | | | `dietaryRestrictions` | `String` | `No` | `-` | `body` | `dietaryRestrictions` | | **Description:** | List of user dietary restrictions or allergies for meal plan customization. | | | | | | | | | | | | | `fitnessGoal` | `Enum` | `No` | `-` | `body` | `fitnessGoal` | | **Description:** | User's primary fitness goal driving program and nutrition recommendations. | | | | | | | | | | | | | `height` | `Float` | `No` | `-` | `body` | `height` | | **Description:** | User's height in centimeters, used for BMR and TDEE calculations. | | | | | | | | | | | | | `sex` | `Enum` | `No` | `-` | `body` | `sex` | | **Description:** | User's biological sex, used for BMR calculations and program customization. | | | | | | | | | | | | | `trainingExperience` | `Enum` | `No` | `-` | `body` | `trainingExperience` | | **Description:** | User's training experience level, influencing program complexity and progression rates. | | | | | | | | | | | | | `weeklyTrainingDays` | `Integer` | `No` | `-` | `body` | `weeklyTrainingDays` | | **Description:** | Number of days per week the user is available to train, used for program split selection. | | | | | | | | | | | | | `weight` | `Float` | `No` | `-` | `body` | `weight` | | **Description:** | User's current body weight in kilograms, used for calorie and macro calculations. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateProfile` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[2].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { fullname: this.fullname, avatar: this.avatar, activityLevel: this.activityLevel, availableEquipment: this.availableEquipment ? this.availableEquipment : ( this.availableEquipment_remove ? sequelize.fn('array_remove', sequelize.col('availableEquipment'), this.availableEquipment_remove) : (this.availableEquipment_append ? sequelize.fn('array_append', sequelize.col('availableEquipment'), this.availableEquipment_append) : undefined)) , country: this.country, dateOfBirth: this.dateOfBirth, dietaryRestrictions: this.dietaryRestrictions ? this.dietaryRestrictions : ( this.dietaryRestrictions_remove ? sequelize.fn('array_remove', sequelize.col('dietaryRestrictions'), this.dietaryRestrictions_remove) : (this.dietaryRestrictions_append ? sequelize.fn('array_append', sequelize.col('dietaryRestrictions'), this.dietaryRestrictions_append) : undefined)) , fitnessGoal: this.fitnessGoal, height: this.height, sex: this.sex, trainingExperience: this.trainingExperience, weeklyTrainingDays: this.weeklyTrainingDays, weight: this.weight, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateProfile` api has got 14 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | false | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/profile/:userId** ```js axios({ method: 'PATCH', url: `/v1/profile/${userId}`, data: { fullname:"String", avatar:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Create User` # Business API Design Specification - `Create User` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createUser` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createUser` Business API is designed to handle a `create` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This api is used by admin roles to create a new user manually from admin panels ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `user-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createUser` Business API includes a REST controller that can be triggered via the following route: `/v1/users` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `createUser` Business API includes a gRPC controller that can be triggered via the following function: `createUser()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createUser` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createUser` Business API has 16 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `No` | `-` | `body` | `userId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `avatar` | `String` | `No` | `-` | `body` | `avatar` | | **Description:** | The avatar url of the user. If not sent, a default random one will be generated. | | | | | | | | | | | | | `email` | `String` | `Yes` | `-` | `body` | `email` | | **Description:** | A string value to represent the user's email. | | | | | | | | | | | | | `password` | `String` | `Yes` | `-` | `body` | `password` | | **Description:** | A string value to represent the user's password. It will be stored as hashed. | | | | | | | | | | | | | `fullname` | `String` | `Yes` | `-` | `body` | `fullname` | | **Description:** | A string value to represent the fullname of the user | | | | | | | | | | | | | `activityLevel` | `Enum` | `No` | `-` | `body` | `activityLevel` | | **Description:** | User's general daily activity level, used as the TDEE activity multiplier. | | | | | | | | | | | | | `availableEquipment` | `String` | `No` | `-` | `body` | `availableEquipment` | | **Description:** | List of equipment available to the user for training program generation. | | | | | | | | | | | | | `country` | `String` | `No` | `-` | `body` | `country` | | **Description:** | User's country of residence, used for regional food suggestions and cuisine preferences. | | | | | | | | | | | | | `dateOfBirth` | `Date` | `No` | `-` | `body` | `dateOfBirth` | | **Description:** | User's date of birth, used for age-based calorie and program calculations. | | | | | | | | | | | | | `dietaryRestrictions` | `String` | `No` | `-` | `body` | `dietaryRestrictions` | | **Description:** | List of user dietary restrictions or allergies for meal plan customization. | | | | | | | | | | | | | `fitnessGoal` | `Enum` | `No` | `-` | `body` | `fitnessGoal` | | **Description:** | User's primary fitness goal driving program and nutrition recommendations. | | | | | | | | | | | | | `height` | `Float` | `No` | `-` | `body` | `height` | | **Description:** | User's height in centimeters, used for BMR and TDEE calculations. | | | | | | | | | | | | | `sex` | `Enum` | `Yes` | `-` | `body` | `sex` | | **Description:** | User's biological sex, used for BMR calculations and program customization. | | | | | | | | | | | | | `trainingExperience` | `Enum` | `No` | `-` | `body` | `trainingExperience` | | **Description:** | User's training experience level, influencing program complexity and progression rates. | | | | | | | | | | | | | `weeklyTrainingDays` | `Integer` | `No` | `-` | `body` | `weeklyTrainingDays` | | **Description:** | Number of days per week the user is available to train, used for program split selection. | | | | | | | | | | | | | `weight` | `Float` | `No` | `-` | `body` | `weight` | | **Description:** | User's current body weight in kilograms, used for calorie and macro calculations. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. * `avatar`: ```javascript this.avatar = runMScript(() => (this.avatar ? `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon` : null), {"path":"services[0].businessLogic[3].customParameters[0].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createUser` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin`, `saasAdmin`, `tenantAdmin`, `tenantOwner]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.userId, email: this.email, password: this.hashString(this.password), fullname: this.fullname, avatar: this.avatar, activityLevel: this.activityLevel, availableEquipment: this.availableEquipment, country: this.country, dateOfBirth: this.dateOfBirth, dietaryRestrictions: this.dietaryRestrictions, fitnessGoal: this.fitnessGoal, height: this.height, sex: this.sex, trainingExperience: this.trainingExperience, weeklyTrainingDays: this.weeklyTrainingDays, weight: this.weight, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Action : validateEmail **Action Type**: `ValidationAction` Validates that the provided email address has a valid format ```js class Api { async validateEmail() { const isValid = runMScript( () => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email), { path: "services[0].businessLogic[3].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError("InvalidEmailFormat"); } return isValid; } } ``` --- ### [6] Action : fetchArchivedUser **Action Type**: `FetchObjectAction` Check and get if any deleted user exists with the same identifier ```js class Api { async fetchArchivedUser() { // Fetch Object on childObject user const userQuery = runMScript( () => ({ $and: [ { email: this.email, isActive: false }, { _archivedAt: { $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), }, }, ], }), { path: "services[0].businessLogic[3].actions.fetchObjectActions[0].whereClause", }, ); const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getUserByQuery(scriptQuery); return data ? { id: data["id"], } : null; } } ``` --- ### [7] Action : checkArchivedUser **Action Type**: `ValidationAction` Prevents re-register of a user when their profile is still in 30days archive ```js class Api { async checkArchivedUser() { const isError = runMScript(() => this.archivedUser?.email != null, { path: "services[0].businessLogic[3].actions.validationActions[1].validationScript", }); if (isError) { throw new BadRequestError("ThisProfileIsArchivedPleaseLoginToRestore"); } return isError; } } ``` --- ### [8] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [9] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [11] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [12] Action : writeVerificationNeedsToResponse **Action Type**: `AddToResponseAction` Set if email or mobile verification needed ```js class Api { async writeVerificationNeedsToResponse() { try { this.output["emailVerificationNeeded"] = runMScript( () => !this.user?.emailVerified, { path: "services[0].businessLogic[3].actions.addToResponseActions[0].context[0].contextValue", }, ); this.output["mobileVerificationNeeded"] = runMScript(() => false, { path: "services[0].businessLogic[3].actions.addToResponseActions[0].context[1].contextValue", }); return true; } catch (error) { console.error("AddToResponseAction error:", error); throw error; } } } ``` --- ### [13] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [14] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createUser` api has got 15 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | email | String | true | request.body?.["email"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | true | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/users** ```js axios({ method: 'POST', url: '/v1/users', data: { avatar:"String", email:"String", password:"String", fullname:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete User` # Business API Design Specification - `Delete User` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deleteUser` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deleteUser` Business API is designed to handle a `delete` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This api is used by admins to delete user profiles. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `user-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deleteUser` Business API includes a REST controller that can be triggered via the following route: `/v1/users/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `deleteUser` Business API includes a gRPC controller that can be triggered via the following function: `deleteUser()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deleteUser` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteUser` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deleteUser` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[4].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Action : setRolesOrder **Action Type**: `CreateObjectAction` Sets the hiyerarchy of the roles to check user permissions on other users ```js class Api { async setRolesOrder() { // Construct base object const obj = {}; // Merge dynamic object Object.assign( obj, runMScript( () => ({ superAdmin: 20, saasAdmin: 19, admin: 18, tenantOwner: 17, tenantAdmin: 16, saasUser: 15, tenantUser: 0, user: 0, }), { path: "services[0].businessLogic[4].actions.createObjectActions[0].mergeObject", }, ), ); return obj; } } ``` --- ### [7] Action : protectSuperAdmin **Action Type**: `ValidationAction` Prevents deletion of the SuperAdmin account. This safeguard ensures that the SuperAdmin userId cannot be removed under any circumstances. ```js class Api { async protectSuperAdmin() { const isError = runMScript(() => this.userId == this.auth?.superAdminId, { path: "services[0].businessLogic[4].actions.validationActions[0].validationScript", }); if (isError) { throw new BadRequestError("SuperAdminCantBeDeleted"); } return isError; } } ``` --- ### [8] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [9] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [10] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [11] Action : protectHigherRole **Action Type**: `ValidationAction` Prevents the delete of a higher or equal user role ```js class Api { async protectHigherRole() { const isValid = runMScript( () => (this._r[this.session?.roleId] ?? 0) > (this._r[this.user?.roleId] ?? 0), { path: "services[0].businessLogic[4].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new BadRequestError("AHigherOrEqualUserRoleCantBeDeleted"); } return isValid; } } ``` --- ### [12] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [13] Action : deleteUserSessions **Action Type**: `FunctionCallAction` Makes a call to this.auth to delete the sessions of the deleted user. ```js class Api { async deleteUserSessions() { try { return await runMScript( () => (async () => await (async (userId) => { await this.auth.deleteUserSessions(userId); })(this.userId))(), { path: "services[0].businessLogic[4].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction deleteUserSessions:", err); throw err; } } } ``` --- ### [14] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [15] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [16] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deleteUser` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/users/:userId** ```js axios({ method: 'DELETE', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Archive Profile` # Business API Design Specification - `Archive Profile` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `archiveProfile` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `archiveProfile` Business API is designed to handle a `delete` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This api is used by users to archive their profiles. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `profile-archived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `archiveProfile` Business API includes a REST controller that can be triggered via the following route: `/v1/archiveprofile/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `archiveProfile` Business API includes a gRPC controller that can be triggered via the following function: `archiveProfile()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `archiveProfile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `archiveProfile` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `archiveProfile` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[5].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Action : protectSuperAdmin **Action Type**: `ValidationAction` Prevents deletion of the SuperAdmin account. This safeguard ensures that the SuperAdmin userId cannot be removed under any circumstances. ```js class Api { async protectSuperAdmin() { const isError = runMScript(() => this.userId == this.auth?.superAdminId, { path: "services[0].businessLogic[5].actions.validationActions[0].validationScript", }); if (isError) { throw new BadRequestError("SuperAdminCantBeDeleted"); } return isError; } } ``` --- ### [7] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [8] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [9] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [10] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [11] Action : deleteUserSessions **Action Type**: `FunctionCallAction` Makes a call to this.auth to delete the sessions of the deleted user. ```js class Api { async deleteUserSessions() { try { return await runMScript( () => (async () => await (async (userId) => { await this.auth.deleteUserSessions(userId); })(this.userId))(), { path: "services[0].businessLogic[5].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction deleteUserSessions:", err); throw err; } } } ``` --- ### [12] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [13] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [14] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `archiveProfile` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/archiveprofile/:userId** ```js axios({ method: 'DELETE', url: `/v1/archiveprofile/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Users` # Business API Design Specification - `List Users` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listUsers` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listUsers` Business API is designed to handle a `list` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description The list of users is filtered by the tenantId. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `users-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listUsers` Business API includes a REST controller that can be triggered via the following route: `/v1/users` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `listUsers` Business API includes a gRPC controller that can be triggered via the following function: `listUsers()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listUsers` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listUsers` Business API has 8 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listUsers` api supports 8 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `email` Filter **Type:** `String` **Description:** A string value to represent the user's email. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?email=` (matches any string containing the value, case-insensitive) - Multiple values: `?email=&email=` (matches records containing any of the values) - Null check: `?email=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/users?email=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/users?email=laptop&email=phone&email=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/users?email=null ``` #### `fullname` Filter **Type:** `String` **Description:** A string value to represent the fullname of the user **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?fullname=` (matches any string containing the value, case-insensitive) - Multiple values: `?fullname=&fullname=` (matches records containing any of the values) - Null check: `?fullname=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/users?fullname=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/users?fullname=laptop&fullname=phone&fullname=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/users?fullname=null ``` #### `roleId` Filter **Type:** `String` **Description:** A string value to represent the roleId of the user. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?roleId=` (matches any string containing the value, case-insensitive) - Multiple values: `?roleId=&roleId=` (matches records containing any of the values) - Null check: `?roleId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/users?roleId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/users?roleId=laptop&roleId=phone&roleId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/users?roleId=null ``` #### `activityLevel` Filter **Type:** `Enum` **Description:** User's general daily activity level, used as the TDEE activity multiplier. **Location:** Query Parameter **Usage:** - Single value: `?activityLevel=` (case-insensitive) - Multiple values: `?activityLevel=&activityLevel=` - Null check: `?activityLevel=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/users?activityLevel=active // Get records with multiple enum values (use multiple parameters) GET /v1/users?activityLevel=active&activityLevel=pending // Get records without this field GET /v1/users?activityLevel=null ``` #### `country` Filter **Type:** `String` **Description:** User's country of residence, used for regional food suggestions and cuisine preferences. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?country=` (matches any string containing the value, case-insensitive) - Multiple values: `?country=&country=` (matches records containing any of the values) - Null check: `?country=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/users?country=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/users?country=laptop&country=phone&country=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/users?country=null ``` #### `fitnessGoal` Filter **Type:** `Enum` **Description:** User's primary fitness goal driving program and nutrition recommendations. **Location:** Query Parameter **Usage:** - Single value: `?fitnessGoal=` (case-insensitive) - Multiple values: `?fitnessGoal=&fitnessGoal=` - Null check: `?fitnessGoal=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/users?fitnessGoal=active // Get records with multiple enum values (use multiple parameters) GET /v1/users?fitnessGoal=active&fitnessGoal=pending // Get records without this field GET /v1/users?fitnessGoal=null ``` #### `sex` Filter **Type:** `Enum` **Description:** User's biological sex, used for BMR calculations and program customization. **Location:** Query Parameter **Usage:** - Single value: `?sex=` (case-insensitive) - Multiple values: `?sex=&sex=` - Null check: `?sex=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/users?sex=active // Get records with multiple enum values (use multiple parameters) GET /v1/users?sex=active&sex=pending // Get records without this field GET /v1/users?sex=null ``` #### `trainingExperience` Filter **Type:** `Enum` **Description:** User's training experience level, influencing program complexity and progression rates. **Location:** Query Parameter **Usage:** - Single value: `?trainingExperience=` (case-insensitive) - Multiple values: `?trainingExperience=&trainingExperience=` - Null check: `?trainingExperience=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/users?trainingExperience=active // Get records with multiple enum values (use multiple parameters) GET /v1/users?trainingExperience=active&trainingExperience=pending // Get records without this field GET /v1/users?trainingExperience=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listUsers` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin, admin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[0].businessLogic[6].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ id asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listUsers` api has 8 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | email | String | No | A string value to represent the user's email. | | fullname | String | No | A string value to represent the fullname of the user | | roleId | String | No | A string value to represent the roleId of the user. | | activityLevel | Enum | No | User's general daily activity level, used as the TDEE activity multiplier. | | country | String | No | User's country of residence, used for regional food suggestions and cuisine preferences. | | fitnessGoal | Enum | No | User's primary fitness goal driving program and nutrition recommendations. | | sex | Enum | No | User's biological sex, used for BMR calculations and program customization. | | trainingExperience | Enum | No | User's training experience level, influencing program complexity and progression rates. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/users** ```js axios({ method: 'GET', url: '/v1/users', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // email: '' // Filter by email // fullname: '' // Filter by fullname // roleId: '' // Filter by roleId // activityLevel: '' // Filter by activityLevel // country: '' // Filter by country // fitnessGoal: '' // Filter by fitnessGoal // sex: '' // Filter by sex // trainingExperience: '' // Filter by trainingExperience } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`users`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Search Users` # Business API Design Specification - `Search Users` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `searchUsers` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `searchUsers` Business API is designed to handle a `list` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description The list of users is filtered by the tenantId. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `users-searched` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `searchUsers` Business API includes a REST controller that can be triggered via the following route: `/v1/searchusers` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `searchUsers` Business API includes a gRPC controller that can be triggered via the following function: `searchUsers()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `searchUsers` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `searchUsers` Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `keyword` | `String` | `Yes` | `-` | `query` | `keyword` | | **Description:** | - | | | | | | | | | | | | ### Filter Parameters The `searchUsers` api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `roleId` Filter **Type:** `String` **Description:** A string value to represent the roleId of the user. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?roleId=` (matches any string containing the value, case-insensitive) - Multiple values: `?roleId=&roleId=` (matches records containing any of the values) - Null check: `?roleId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/searchusers?roleId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/searchusers?roleId=laptop&roleId=phone&roleId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/searchusers?roleId=null ``` #### `activityLevel` Filter **Type:** `Enum` **Description:** User's general daily activity level, used as the TDEE activity multiplier. **Location:** Query Parameter **Usage:** - Single value: `?activityLevel=` (case-insensitive) - Multiple values: `?activityLevel=&activityLevel=` - Null check: `?activityLevel=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/searchusers?activityLevel=active // Get records with multiple enum values (use multiple parameters) GET /v1/searchusers?activityLevel=active&activityLevel=pending // Get records without this field GET /v1/searchusers?activityLevel=null ``` #### `country` Filter **Type:** `String` **Description:** User's country of residence, used for regional food suggestions and cuisine preferences. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?country=` (matches any string containing the value, case-insensitive) - Multiple values: `?country=&country=` (matches records containing any of the values) - Null check: `?country=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/searchusers?country=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/searchusers?country=laptop&country=phone&country=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/searchusers?country=null ``` #### `fitnessGoal` Filter **Type:** `Enum` **Description:** User's primary fitness goal driving program and nutrition recommendations. **Location:** Query Parameter **Usage:** - Single value: `?fitnessGoal=` (case-insensitive) - Multiple values: `?fitnessGoal=&fitnessGoal=` - Null check: `?fitnessGoal=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/searchusers?fitnessGoal=active // Get records with multiple enum values (use multiple parameters) GET /v1/searchusers?fitnessGoal=active&fitnessGoal=pending // Get records without this field GET /v1/searchusers?fitnessGoal=null ``` #### `sex` Filter **Type:** `Enum` **Description:** User's biological sex, used for BMR calculations and program customization. **Location:** Query Parameter **Usage:** - Single value: `?sex=` (case-insensitive) - Multiple values: `?sex=&sex=` - Null check: `?sex=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/searchusers?sex=active // Get records with multiple enum values (use multiple parameters) GET /v1/searchusers?sex=active&sex=pending // Get records without this field GET /v1/searchusers?sex=null ``` #### `trainingExperience` Filter **Type:** `Enum` **Description:** User's training experience level, influencing program complexity and progression rates. **Location:** Query Parameter **Usage:** - Single value: `?trainingExperience=` (case-insensitive) - Multiple values: `?trainingExperience=&trainingExperience=` - Null check: `?trainingExperience=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/searchusers?trainingExperience=active // Get records with multiple enum values (use multiple parameters) GET /v1/searchusers?trainingExperience=active&trainingExperience=pending // Get records without this field GET /v1/searchusers?trainingExperience=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `searchUsers` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin, admin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[0].businessLogic[7].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ id asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `searchUsers` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | keyword | String | true | request.query?.["keyword"] | The `searchUsers` api has 6 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | roleId | String | No | A string value to represent the roleId of the user. | | activityLevel | Enum | No | User's general daily activity level, used as the TDEE activity multiplier. | | country | String | No | User's country of residence, used for regional food suggestions and cuisine preferences. | | fitnessGoal | Enum | No | User's primary fitness goal driving program and nutrition recommendations. | | sex | Enum | No | User's biological sex, used for BMR calculations and program customization. | | trainingExperience | Enum | No | User's training experience level, influencing program complexity and progression rates. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/searchusers** ```js axios({ method: 'GET', url: '/v1/searchusers', data: { }, params: { keyword:'"String"', // Filter parameters (see Filter Parameters section for usage examples) // roleId: '' // Filter by roleId // activityLevel: '' // Filter by activityLevel // country: '' // Filter by country // fitnessGoal: '' // Filter by fitnessGoal // sex: '' // Filter by sex // trainingExperience: '' // Filter by trainingExperience } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`users`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Update Userrole` # Business API Design Specification - `Update Userrole` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateUserRole` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateUserRole` Business API is designed to handle a `update` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used by admin roles to update the user role.The default role is user when a user is registered. A user's role can be updated by superAdmin or admin ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `userrole-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateUserRole` Business API includes a REST controller that can be triggered via the following route: `/v1/userrole/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `updateUserRole` Business API includes a gRPC controller that can be triggered via the following function: `updateUserRole()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateUserRole` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateUserRole` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `roleId` | `String` | `Yes` | `-` | `body` | `roleId` | | **Description:** | The new roleId of the user to be updated | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateUserRole` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[8].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { roleId: runMScript(() => (this.roleId), {"path":"services[0].businessLogic[8].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // roleId parameter is closed to update by client request // include it in data clause unless you are sure roleId: runMScript(() => (this.roleId), {"path":"services[0].businessLogic[8].dataClause.customData[0].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Action : setRolesOrder **Action Type**: `CreateObjectAction` Sets the hiyerarchy of the roles to check user permissions on other users ```js class Api { async setRolesOrder() { // Construct base object const obj = {}; // Merge dynamic object Object.assign( obj, runMScript( () => ({ superAdmin: 20, saasAdmin: 19, admin: 18, tenantOwner: 17, tenantAdmin: 16, saasUser: 15, tenantUser: 0, user: 0, }), { path: "services[0].businessLogic[8].actions.createObjectActions[0].mergeObject", }, ), ); return obj; } } ``` --- ### [7] Action : preventHigherRoleSet **Action Type**: `ValidationAction` Prevents to set a user's role as higher than or equal to the setter role ```js class Api { async preventHigherRoleSet() { const isValid = runMScript( () => (this._r[this.session.roleId] ?? 0) > (this._r[this.roleId] ?? 0), { path: "services[0].businessLogic[8].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError("AHigherRoleCantBeAssigned"); } return isValid; } } ``` --- ### [8] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [9] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [10] Action : protectHigherRole **Action Type**: `ValidationAction` Prevents the update of a higher or equal user role ```js class Api { async protectHigherRole() { const isValid = runMScript( () => (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0), { path: "services[0].businessLogic[8].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new BadRequestError("AHigherUserRoleCantBeChanged"); } return isValid; } } ``` --- ### [11] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [12] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [13] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [14] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [15] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [16] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateUserRole` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | roleId | String | true | request.body?.["roleId"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/userrole/:userId** ```js axios({ method: 'PATCH', url: `/v1/userrole/${userId}`, data: { roleId:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Userpassword` # Business API Design Specification - `Update Userpassword` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateUserPassword` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateUserPassword` Business API is designed to handle a `update` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to update the password of users in the profile page by users themselves ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `userpassword-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateUserPassword` Business API includes a REST controller that can be triggered via the following route: `/v1/userpassword/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `updateUserPassword` Business API includes a gRPC controller that can be triggered via the following function: `updateUserPassword()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateUserPassword` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateUserPassword` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `oldPassword` | `String` | `Yes` | `-` | `body` | `oldPassword` | | **Description:** | The old password of the user that will be overridden bu the new one. Send for double check. | | | | | | | | | | | | | `newPassword` | `String` | `Yes` | `-` | `body` | `newPassword` | | **Description:** | The new password of the user to be updated | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. * `newPassword`: ```javascript this.newPassword = runMScript(() => (this.newPassword ? this.hashString(this.newPassword) : null), {"path":"services[0].businessLogic[9].customParameters[1].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateUserPassword` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[9].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { password: runMScript(() => (this.newPassword), {"path":"services[0].businessLogic[9].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // password parameter is closed to update by client request // include it in data clause unless you are sure password: runMScript(() => (this.newPassword), {"path":"services[0].businessLogic[9].dataClause.customData[0].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Action : checkOldPassword **Action Type**: `ValidationAction` Check if the current password mathces the old password. It is done after the instance is fetched. ```js class Api { async checkOldPassword() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.hashCompare(this.oldPassword, this.user.password), { path: "services[0].businessLogic[9].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError("TheOldPasswordDoesNotMatch"); } return isValid; } } ``` --- ### [10] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [11] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [12] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [13] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [14] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateUserPassword` api has got 3 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | oldPassword | String | true | request.body?.["oldPassword"] | | newPassword | String | true | request.body?.["newPassword"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/userpassword/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpassword/${userId}`, data: { oldPassword:"String", newPassword:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Userpasswordbyadmin` # Business API Design Specification - `Update Userpasswordbyadmin` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateUserPasswordByAdmin` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateUserPasswordByAdmin` Business API is designed to handle a `update` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `userpasswordbyadmin-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateUserPasswordByAdmin` Business API includes a REST controller that can be triggered via the following route: `/v1/userpasswordbyadmin/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `updateUserPasswordByAdmin` Business API includes a gRPC controller that can be triggered via the following function: `updateUserPasswordByAdmin()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateUserPasswordByAdmin` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateUserPasswordByAdmin` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `password` | `String` | `Yes` | `-` | `body` | `password` | | **Description:** | The new password of the user to be updated | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. * `password`: ```javascript this.password = runMScript(() => (this.password ? this.hashString(this.password) : null), {"path":"services[0].businessLogic[10].customParameters[0].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateUserPasswordByAdmin` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[10].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { password: runMScript(() => (this.password), {"path":"services[0].businessLogic[10].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // password parameter is closed to update by client request // include it in data clause unless you are sure password: runMScript(() => (this.password), {"path":"services[0].businessLogic[10].dataClause.customData[0].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Action : setRolesOrder **Action Type**: `CreateObjectAction` Sets the hiyerarchy of the roles to check user permissions on other users ```js class Api { async setRolesOrder() { // Construct base object const obj = {}; // Merge dynamic object Object.assign( obj, runMScript( () => ({ superAdmin: 20, saasAdmin: 19, admin: 18, tenantOwner: 17, tenantAdmin: 16, saasUser: 15, tenantUser: 14, user: 13, }), { path: "services[0].businessLogic[10].actions.createObjectActions[0].mergeObject", }, ), ); return obj; } } ``` --- ### [10] Action : protectHigherRole **Action Type**: `ValidationAction` Prevents the update of a higher or equal user role ```js class Api { async protectHigherRole() { const isValid = runMScript( () => (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0), { path: "services[0].businessLogic[10].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError("AHigherUserCantBeUpdated"); } return isValid; } } ``` --- ### [11] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [12] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [13] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [14] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [15] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateUserPasswordByAdmin` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | password | String | true | request.body?.["password"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/userpasswordbyadmin/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpasswordbyadmin/${userId}`, data: { password:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Briefuser` # Business API Design Specification - `Get Briefuser` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getBriefUser` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getBriefUser` Business API is designed to handle a `get` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used by public to get simple user profile information. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `briefuser-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getBriefUser` Business API includes a REST controller that can be triggered via the following route: `/v1/briefuser/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `getBriefUser` Business API includes a gRPC controller that can be triggered via the following function: `getBriefUser()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getBriefUser` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getBriefUser` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getBriefUser` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API is **public** and can be accessed without login (`loginRequired = false`). --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `id`,`fullname`,`avatar` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[11].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getBriefUser` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/briefuser/:userId** ```js axios({ method: 'GET', url: `/v1/briefuser/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "isActive": true } } ``` --- ### Business API Design Specification - `Stream Test` # Business API Design Specification - `Stream Test` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `streamTest` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `streamTest` Business API is designed to handle a `get` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Test API for iterator action streaming via SSE. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `streamTest` Business API includes a REST controller that can be triggered via the following route: `/v1/streamtest/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `streamTest` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `streamTest` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `streamTest` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[12].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `streamTest` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/streamtest/:userId** ```js axios({ method: 'GET', url: `/v1/streamtest/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Register User` # Business API Design Specification - `Register User` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `registerUser` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `registerUser` Business API is designed to handle a `create` operation on the `User` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This api is used by public users to register themselves ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `user-registered` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `registerUser` Business API includes a REST controller that can be triggered via the following route: `/v1/registeruser` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### gRPC Controller The `registerUser` Business API includes a gRPC controller that can be triggered via the following function: `registerUser()` By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `registerUser` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `registerUser` Business API has 17 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `No` | `-` | `body` | `userId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `avatar` | `String` | `No` | `-` | `body` | `avatar` | | **Description:** | The avatar url of the user. If not sent, a default random one will be generated. | | | | | | | | | | | | | `socialCode` | `String` | `No` | `-` | `body` | `socialCode` | | **Description:** | Send this social code if it is sent to you after a social login authetication of an unregistred user. The users profile data will be complemented from the autheticated social profile using this code. If you provide the social code there is no need to give full profile data of the user, just give the ones that are not included in social profiles. | | | | | | | | | | | | | `password` | `String` | `Yes` | `-` | `body` | `password` | | **Description:** | The password defined by the the user that is being registered. | | | | | | | | | | | | | `fullname` | `String` | `Yes` | `-` | `body` | `fullname` | | **Description:** | The fullname defined by the the user that is being registered. | | | | | | | | | | | | | `email` | `String` | `Yes` | `-` | `body` | `email` | | **Description:** | The email defined by the the user that is being registered. | | | | | | | | | | | | | `activityLevel` | `Enum` | `No` | `-` | `body` | `activityLevel` | | **Description:** | User's general daily activity level, used as the TDEE activity multiplier. | | | | | | | | | | | | | `availableEquipment` | `String` | `No` | `-` | `body` | `availableEquipment` | | **Description:** | List of equipment available to the user for training program generation. | | | | | | | | | | | | | `country` | `String` | `No` | `-` | `body` | `country` | | **Description:** | User's country of residence, used for regional food suggestions and cuisine preferences. | | | | | | | | | | | | | `dateOfBirth` | `Date` | `No` | `-` | `body` | `dateOfBirth` | | **Description:** | User's date of birth, used for age-based calorie and program calculations. | | | | | | | | | | | | | `dietaryRestrictions` | `String` | `No` | `-` | `body` | `dietaryRestrictions` | | **Description:** | List of user dietary restrictions or allergies for meal plan customization. | | | | | | | | | | | | | `fitnessGoal` | `Enum` | `No` | `-` | `body` | `fitnessGoal` | | **Description:** | User's primary fitness goal driving program and nutrition recommendations. | | | | | | | | | | | | | `height` | `Float` | `No` | `-` | `body` | `height` | | **Description:** | User's height in centimeters, used for BMR and TDEE calculations. | | | | | | | | | | | | | `sex` | `Enum` | `Yes` | `-` | `body` | `sex` | | **Description:** | User's biological sex, used for BMR calculations and program customization. | | | | | | | | | | | | | `trainingExperience` | `Enum` | `No` | `-` | `body` | `trainingExperience` | | **Description:** | User's training experience level, influencing program complexity and progression rates. | | | | | | | | | | | | | `weeklyTrainingDays` | `Integer` | `No` | `-` | `body` | `weeklyTrainingDays` | | **Description:** | Number of days per week the user is available to train, used for program split selection. | | | | | | | | | | | | | `weight` | `Float` | `No` | `-` | `body` | `weight` | | **Description:** | User's current body weight in kilograms, used for calorie and macro calculations. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. * `avatar`: ```javascript this.avatar = runMScript(() => (this.socialProfile?.avatar ?? (this.avatar ? this.avatar : `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon`)), {"path":"services[0].businessLogic[13].customParameters[0].transform"}) ``` * `password`: ```javascript this.password = runMScript(() => (this.socialProfile ? this.password ?? LIB.common.randomCode() : this.password), {"path":"services[0].businessLogic[13].customParameters[2].transform"}) ``` * `fullname`: ```javascript this.fullname = runMScript(() => (this.socialProfile?.fullname ?? this.fullname), {"path":"services[0].businessLogic[13].customParameters[3].transform"}) ``` * `email`: ```javascript this.email = runMScript(() => (this.socialProfile?.email ?? this.email), {"path":"services[0].businessLogic[13].customParameters[4].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `registerUser` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API is **public** and can be accessed without login (`loginRequired = false`). --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** ```js { emailVerified: runMScript(() => (this.socialProfile?.emailVerified ?? false), {"path":"services[0].businessLogic[13].dataClause.customData[0].value"}), roleId: runMScript(() => (this.socialProfile?.roleId ?? 'user'), {"path":"services[0].businessLogic[13].dataClause.customData[1].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.userId, email: this.email, password: this.hashString(this.password), fullname: this.fullname, avatar: this.avatar, activityLevel: this.activityLevel, availableEquipment: this.availableEquipment, country: this.country, dateOfBirth: this.dateOfBirth, dietaryRestrictions: this.dietaryRestrictions, fitnessGoal: this.fitnessGoal, height: this.height, sex: this.sex, trainingExperience: this.trainingExperience, weeklyTrainingDays: this.weeklyTrainingDays, weight: this.weight, emailVerified: runMScript(() => (this.socialProfile?.emailVerified ?? false), {"path":"services[0].businessLogic[13].dataClause.customData[0].value"}), roleId: runMScript(() => (this.socialProfile?.roleId ?? 'user'), {"path":"services[0].businessLogic[13].dataClause.customData[1].value"}), isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Action : validateEmail **Action Type**: `ValidationAction` Validates that the provided email address has a valid format ```js class Api { async validateEmail() { const isValid = runMScript( () => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email), { path: "services[0].businessLogic[13].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError("InvalidEmailFormat"); } return isValid; } } ``` --- ### [6] Action : fetchArchivedUser **Action Type**: `FetchObjectAction` Check and get if any deleted user(in 30 days) exists with the same identifier ```js class Api { async fetchArchivedUser() { // Fetch Object on childObject user const userQuery = runMScript( () => ({ $and: [ { email: this.email, isActive: false }, { _archivedAt: { $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), }, }, ], }), { path: "services[0].businessLogic[13].actions.fetchObjectActions[0].whereClause", }, ); const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getUserByQuery(scriptQuery); return data ? { id: data["id"], } : null; } } ``` --- ### [7] Action : checkArchivedUser **Action Type**: `ValidationAction` Prevents re-register of a user when their profile is still in 30days archive ```js class Api { async checkArchivedUser() { const isError = runMScript(() => this.archivedUser?.email != null, { path: "services[0].businessLogic[13].actions.validationActions[1].validationScript", }); if (isError) { throw new BadRequestError("YourProfileIsArchivedPleaseLoginToRestore"); } return isError; } } ``` --- ### [8] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [9] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [11] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [12] Action : writeVerificationNeedsToResponse **Action Type**: `AddToResponseAction` Set if email or mobile verification needed ```js class Api { async writeVerificationNeedsToResponse() { try { this.output["emailVerificationNeeded"] = runMScript( () => !this.user?.emailVerified, { path: "services[0].businessLogic[13].actions.addToResponseActions[0].context[0].contextValue", }, ); this.output["mobileVerificationNeeded"] = runMScript(() => false, { path: "services[0].businessLogic[13].actions.addToResponseActions[0].context[1].contextValue", }); return true; } catch (error) { console.error("AddToResponseAction error:", error); throw error; } } } ``` --- ### [13] Action : autoLoginAfterRegister **Action Type**: `FunctionCallAction` If no email or mobile verification is needed after registration, automatically create a login session and return the access token in the registration response. This provides a seamless register-and-login experience. ```js class Api { async autoLoginAfterRegister() { try { return await runMScript( () => (async () => await (async () => { try { if ( this.output.emailVerificationNeeded || this.output.mobileVerificationNeeded ) return; const identifier = this.output[this.dataName]?.email; if (!identifier) return; const { createSessionManager } = require("sessionLayer"); const sm = createSessionManager(); await sm.setLoginToRequest(this.request, null, { userField: "email", subjectClaim: identifier, }); this.output.accessToken = sm.accessToken; this.output.autoLoginSession = sm.session; this.request.autoLoginToken = sm.accessToken; console.log( "Auto-login after registration successful for:", identifier, ); } catch (autoLoginErr) { console.log( "Auto-login after registration failed:", autoLoginErr.message, ); } })())(), { path: "services[0].businessLogic[13].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction autoLoginAfterRegister:", err); throw err; } } } ``` --- ### [14] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [15] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `registerUser` api has got 15 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | email | String | true | request.body?.["email"] | | activityLevel | Enum | false | request.body?.["activityLevel"] | | availableEquipment | String | false | request.body?.["availableEquipment"] | | country | String | false | request.body?.["country"] | | dateOfBirth | Date | false | request.body?.["dateOfBirth"] | | dietaryRestrictions | String | false | request.body?.["dietaryRestrictions"] | | fitnessGoal | Enum | false | request.body?.["fitnessGoal"] | | height | Float | false | request.body?.["height"] | | sex | Enum | true | request.body?.["sex"] | | trainingExperience | Enum | false | request.body?.["trainingExperience"] | | weeklyTrainingDays | Integer | false | request.body?.["weeklyTrainingDays"] | | weight | Float | false | request.body?.["weight"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/registeruser** ```js axios({ method: 'POST', url: '/v1/registeruser', data: { avatar:"String", password:"String", fullname:"String", email:"String", activityLevel:"Enum", availableEquipment:"String", country:"String", dateOfBirth:"Date", dietaryRestrictions:"String", fitnessGoal:"Enum", height:"Float", sex:"Enum", trainingExperience:"Enum", weeklyTrainingDays:"Integer", weight:"Float", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`user`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "activityLevel": "Enum", "activityLevel_idx": "Integer", "availableEquipment": "String", "country": "String", "dateOfBirth": "Date", "dietaryRestrictions": "String", "fitnessGoal": "Enum", "fitnessGoal_idx": "Integer", "height": "Float", "sex": "Enum", "sex_idx": "Integer", "trainingExperience": "Enum", "trainingExperience_idx": "Integer", "weeklyTrainingDays": "Integer", "weight": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Useravatarsfile` # Business API Design Specification - `Get Useravatarsfile` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getUserAvatarsFile` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getUserAvatarsFile` Business API is designed to handle a `get` operation on the `UserAvatarsFile` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `useravatarsfile-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getUserAvatarsFile` Business API includes a REST controller that can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getUserAvatarsFile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getUserAvatarsFile` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userAvatarsFileId` | `ID` | `Yes` | `-` | `urlpath` | `userAvatarsFileId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getUserAvatarsFile` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.userAvatarsFileId}), {"path":"services[0].businessLogic[14].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getUserAvatarsFile` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'GET', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`userAvatarsFile`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `List Useravatarsfiles` # Business API Design Specification - `List Useravatarsfiles` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listUserAvatarsFiles` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listUserAvatarsFiles` Business API is designed to handle a `list` operation on the `UserAvatarsFile` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `useravatarsfiles-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listUserAvatarsFiles` Business API includes a REST controller that can be triggered via the following route: `/v1/useravatarsfiles` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listUserAvatarsFiles` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listUserAvatarsFiles` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listUserAvatarsFiles` api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `mimeType` Filter **Type:** `String` **Description:** MIME type of the uploaded file (e.g., image/png, application/pdf). **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?mimeType=` (matches any string containing the value, case-insensitive) - Multiple values: `?mimeType=&mimeType=` (matches records containing any of the values) - Null check: `?mimeType=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/useravatarsfiles?mimeType=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/useravatarsfiles?mimeType=laptop&mimeType=phone&mimeType=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/useravatarsfiles?mimeType=null ``` #### `ownerId` Filter **Type:** `ID` **Description:** ID of the user who uploaded the file (from session). **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?ownerId=` - Multiple values: `?ownerId=&ownerId=` - Null check: `?ownerId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/useravatarsfiles?ownerId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/useravatarsfiles?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/useravatarsfiles?ownerId=null ``` #### `userId` Filter **Type:** `ID` **Description:** Reference to the owner user record. **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/useravatarsfiles?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/useravatarsfiles?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/useravatarsfiles?userId=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listUserAvatarsFiles` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js null ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listUserAvatarsFiles` api has 3 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | mimeType | String | No | MIME type of the uploaded file (e.g., image/png, application/pdf). | | ownerId | ID | No | ID of the user who uploaded the file (from session). | | userId | ID | No | Reference to the owner user record. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles** ```js axios({ method: 'GET', url: '/v1/useravatarsfiles', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // mimeType: '' // Filter by mimeType // ownerId: '' // Filter by ownerId // userId: '' // Filter by userId } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`userAvatarsFiles`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userAvatarsFiles": [ { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Delete Useravatarsfile` # Business API Design Specification - `Delete Useravatarsfile` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deleteUserAvatarsFile` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deleteUserAvatarsFile` Business API is designed to handle a `delete` operation on the `UserAvatarsFile` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `useravatarsfile-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deleteUserAvatarsFile` Business API includes a REST controller that can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deleteUserAvatarsFile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteUserAvatarsFile` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userAvatarsFileId` | `ID` | `Yes` | `-` | `urlpath` | `userAvatarsFileId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deleteUserAvatarsFile` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.userAvatarsFileId}), {"path":"services[0].businessLogic[16].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deleteUserAvatarsFile` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'DELETE', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`userAvatarsFile`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` --- ## Database Buckets ### Database Bucket Design Specification - `userAvatars` # Database Bucket Design Specification - `userAvatars` This document provides a detailed architectural overview of the `userAvatars` database bucket within the `auth` service. It covers the bucket's storage configuration, authorization model, endpoints, and optional owner DataObject pairing. ## Bucket Overview **Description:** User profile avatar images stored in the database. A database bucket stores files as BYTEA columns in PostgreSQL. It is suited for small files such as icons, avatars, documents, and secret files. - **Route Prefix:** `/bucket/userAvatars/` - **Auto-Generated DataObject:** `userAvatarsFile` - **Max File Size:** 5 MB - **Allowed MIME Types:** image/png,image/jpeg,image/webp,image/gif ## Authorization The bucket uses a layered authorization model for both read and write operations: ### Read Access - **Access Level:** `public` Anyone can download files, including anonymous users and via access keys. ### Write Access - **Access Level:** `authenticated` Any authenticated user can upload files. ### Key-Based Access - **Enabled:** Yes Each uploaded file receives a 12-character random access key. Files can be downloaded via this key regardless of other authorization settings, enabling shareable download links. ## Owner DataObject This bucket is paired with an owner DataObject for relational file management. Each uploaded file is linked to a record in the owner DataObject via a foreign key, enabling structured file ownership and access patterns. ## REST Endpoints The following endpoints are auto-generated for this bucket: | Method | Path | Description | Auth | |--------|------|-------------|------| | `POST` | `/bucket/userAvatars/upload` | Upload a file | Authenticated | | `GET` | `/bucket/userAvatars/download/:id` | Download a file by ID | public | | `GET` | `/bucket/userAvatars/download/key/:accessKey` | Download via access key | Public | | `GET` | `/bucket/userAvatars/meta/:id` | Get file metadata | public | | `DELETE` | `/bucket/userAvatars/:id` | Delete a file | Authenticated | ### Upload Request ``` POST /bucket/userAvatars/upload Content-Type: multipart/form-data file: ``` The upload response returns the file metadata including the generated `id` and `accessKey`. ### Download Response The download endpoint returns the raw file bytes with the appropriate `Content-Type` header set from the stored MIME type. ## Auto-Generated DataObject: `userAvatarsFile` The bucket automatically generates a `userAvatarsFile` DataObject with metadata properties: | Property | Type | Description | |----------|------|-------------| | `id` | ID | Unique file identifier (UUID) | | `fileName` | String | Original file name | | `mimeType` | String | MIME type of the file | | `fileSize` | Integer | File size in bytes | | `accessKey` | String | 12-character random access key for shareable links | | `createdAt` | Date | Upload timestamp | | `ownerId` | ID | User ID of uploader (from session) | Standard CRUD APIs are generated for the metadata object, allowing listing, filtering, and management of file records independently of the binary content. --- *This document was generated from the database bucket configuration and should be kept in sync with design changes.* --- # AiCoach Service ## Service Design Specification # 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'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**: 'additionalquota addition' 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 `'pending'` and will be set to `status`property. `paymentResultCanceled` status will be mapped to a local value using `'cancelled'` and will be set to `status` property. `paymentResultFailed` status will be mapped to a local value using `'failed'` and will be set to `status` property. `paymentResultSuccess` status will be mapped to a local value using `'active'` 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'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](/document/businessLogic/createchatmessage) * [Create Coachconversation](/document/businessLogic/createcoachconversation) * [Create Quotaconfig](/document/businessLogic/createquotaconfig) * [Create Weightlog](/document/businessLogic/createweightlog) * [Get Chatmessage](/document/businessLogic/getchatmessage) * [Get Coachconversation](/document/businessLogic/getcoachconversation) * [Get Mealplan](/document/businessLogic/getmealplan) * [Get Moderationrecord](/document/businessLogic/getmoderationrecord) * [Get Myquota](/document/businessLogic/getmyquota) * [Get Planmeal](/document/businessLogic/getplanmeal) * [Get Programexercise](/document/businessLogic/getprogramexercise) * [Get Quotaconfig](/document/businessLogic/getquotaconfig) * [Get Trainingprogram](/document/businessLogic/gettrainingprogram) * [Get Userquota](/document/businessLogic/getuserquota) * [Get Weightlog](/document/businessLogic/getweightlog) * [List Chatmessages](/document/businessLogic/listchatmessages) * [List Coachconversations](/document/businessLogic/listcoachconversations) * [List Mealplans](/document/businessLogic/listmealplans) * [List Moderationrecords](/document/businessLogic/listmoderationrecords) * [List Planmeals](/document/businessLogic/listplanmeals) * [List Programexercises](/document/businessLogic/listprogramexercises) * [List Quotaconfigs](/document/businessLogic/listquotaconfigs) * [List Trainingprograms](/document/businessLogic/listtrainingprograms) * [List Userquotas](/document/businessLogic/listuserquotas) * [List Weightlogs](/document/businessLogic/listweightlogs) * [Update Quotaconfig](/document/businessLogic/updatequotaconfig) * [Delete Moderationrecord](/document/businessLogic/deletemoderationrecord) * [Do Deletemealplan](/document/businessLogic/deletemealplan) * [Do Deletetrainingprogram](/document/businessLogic/deletetrainingprogram) * [Update Moderationrecord](/document/businessLogic/updatemoderationrecord) * [Do Listmymoderationrecords](/document/businessLogic/listmymoderationrecords) * [List Banappeals](/document/businessLogic/listbanappeals) * [Create Banappeal](/document/businessLogic/createbanappeal) * [Update Banappeal](/document/businessLogic/updatebanappeal) * [Create Additionalquota](/document/businessLogic/createadditionalquota) * [Get Myadditionalquota](/document/businessLogic/getmyadditionalquota) * [Get Additionalquotapayment](/document/businessLogic/getadditionalquotapayment) * [List Additionalquotapayments](/document/businessLogic/listadditionalquotapayments) * [Create Additionalquotapayment](/document/businessLogic/createadditionalquotapayment) * [Update Additionalquotapayment](/document/businessLogic/updateadditionalquotapayment) * [Delete Additionalquotapayment](/document/businessLogic/deleteadditionalquotapayment) * [Get Additionalquotapaymentbyorderid](/document/businessLogic/getadditionalquotapaymentbyorderid) * [Get Additionalquotapaymentbypaymentid](/document/businessLogic/getadditionalquotapaymentbypaymentid) * [Start Additionalquotapayment](/document/businessLogic/startadditionalquotapayment) * [Refresh Additionalquotapayment](/document/businessLogic/refreshadditionalquotapayment) * [Callback Additionalquotapayment](/document/businessLogic/callbackadditionalquotapayment) * [Get Paymentcustomerbyuserid](/document/businessLogic/getpaymentcustomerbyuserid) * [List Paymentcustomers](/document/businessLogic/listpaymentcustomers) * [List Paymentcustomermethods](/document/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.* --- ## REST API GUIDE # REST API GUIDE ## aifitapp-aicoach-service **Version:** `1.0.116` 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 ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the AiCoach Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AiCoach Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the AiCoach Service via HTTP requests for purposes such as creating, updating, deleting and querying AiCoach objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the AiCoach Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the AiCoach service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | appaili-access-token| | Cookie | appaili-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the AiCoach service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the AiCoach service. 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` 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` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the AiCoach service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `AiCoach` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `AiCoach` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `AiCoach` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources AiCoach service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### ChatMessage resource *Resource Definition* : Individual chat messages in coach conversations. Stores user, assistant, and system messages with content flagging status and tool call metadata. *ChatMessage Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **content** | Text | | | *Message content* | | **conversationId** | ID | | | *Reference to the parent conversation* | | **flagged** | Boolean | | | *True if the message was detected as off-topic or abusive* | | **role** | Enum | | | *Message sender role* | | **toolCallData** | Text | | | *JSON string of tool call metadata from AI processing* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### role Enum Property *Property Definition* : Message sender role*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **user** | `"user""` | 0 | | **assistant** | `"assistant""` | 1 | | **system** | `"system""` | 2 | ### CoachConversation resource *Resource Definition* : Chat conversation container per user for the AI fitness coach chatbot. *CoachConversation Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **status** | Enum | | | *Conversation status* | | **userId** | ID | | | *Reference to the user who owns this conversation* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Property Definition* : Conversation status*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **closed** | `"closed""` | 1 | ### MealPlan resource *Resource Definition* : 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. *MealPlan Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **carbGrams** | Float | | | *Daily carbohydrate target in grams* | | **dailyCalorieTarget** | Integer | | | *Daily calorie target in kcal* | | **fatGrams** | Float | | | *Daily fat target in grams* | | **notes** | Text | | | *Additional AI-generated nutritional guidance* | | **proteinGrams** | Float | | | *Daily protein target in grams* | | **restDayCalories** | Integer | | | *Calorie target on rest days* | | **restDayCarbGrams** | Float | | | *Carb target on rest days* | | **status** | Enum | | | *Meal plan status* | | **trainingDayCalories** | Integer | | | *Calorie target on training days* | | **trainingDayCarbGrams** | Float | | | *Carb target on training days* | | **userId** | ID | | | *Reference to the user who owns this meal plan* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Property Definition* : Meal plan status*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **archived** | `"archived""` | 1 | ### ModerationRecord resource *Resource Definition* : Tracks user offenses and moderation actions for accurate progressive penalty escalation and admin review. *ModerationRecord Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **action** | Enum | | | *Moderation action taken* | | **offenseType** | String | | | *Description of the violation* | | **reason** | Text | | | *Detailed reason for the moderation action* | | **suspensionExpiresAt** | Date | | | *When a temporary suspension ends (null for lifetime bans and reversals)* | | **userId** | ID | | | *Reference to the user who was moderated* | | **content** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### action Enum Property *Property Definition* : Moderation action taken*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **suspension24h** | `"suspension24h""` | 0 | | **suspension1week** | `"suspension1week""` | 1 | | **lifetimeBan** | `"lifetimeBan""` | 2 | | **banReversal** | `"banReversal""` | 3 | ### PlanMeal resource *Resource Definition* : Individual meals within a meal plan with food details and macro breakdown. Created and modified exclusively by AI tool calls. *PlanMeal Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **carbs** | Float | | | *Carb grams for this meal* | | **fat** | Float | | | *Fat grams for this meal* | | **foods** | Text | | | *Food items and quantities description* | | **mealLabel** | String | | | *Meal label (e.g. breakfast, lunch, dinner, snack)* | | **mealPlanId** | ID | | | *Reference to the parent meal plan* | | **protein** | Float | | | *Protein grams for this meal* | | **sortOrder** | Integer | | | *Display sort order within the meal plan* | | **totalCalories** | Integer | | | *Total calories for this meal* | ### ProgramExercise resource *Resource Definition* : Individual exercises within a training program with sets, reps, RIR targets, and progression rules. Created and modified exclusively by AI tool calls. *ProgramExercise Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **dayLabel** | String | | | *Training day label (e.g. pushDay, upperA, legDay)* | | **exerciseName** | String | | | *Name of the exercise* | | **movementType** | Enum | | | *Movement type classification* | | **muscleGroup** | String | | | *Target muscle group* | | **progressionRule** | Text | | | *Progression instructions (e.g. double progression model)* | | **repMax** | Integer | | | *Maximum rep target* | | **repMin** | Integer | | | *Minimum rep target* | | **rirTarget** | Integer | | | *Reps In Reserve target (0-3)* | | **sets** | Integer | | | *Number of working sets* | | **sortOrder** | Integer | | | *Display sort order within the training day* | | **trainingProgramId** | ID | | | *Reference to the parent training program* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### movementType Enum Property *Property Definition* : Movement type classification*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **lengthened** | `"lengthened""` | 0 | | **shortened** | `"shortened""` | 1 | | **compound** | `"compound""` | 2 | ### QuotaConfig resource *Resource Definition* : System-wide message quota configuration. Admin-managed single record that defines message limits per period. *QuotaConfig Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **quotaLimit** | Integer | | | *Maximum messages allowed per period* | | **quotaPeriod** | Enum | | | *Period over which the quota is measured* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### quotaPeriod Enum Property *Property Definition* : Period over which the quota is measured*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **daily** | `"daily""` | 0 | | **weekly** | `"weekly""` | 1 | | **monthly** | `"monthly""` | 2 | ### TrainingProgram resource *Resource Definition* : 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. *TrainingProgram Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **cardioDurationMinutes** | Integer | | | *Recommended cardio duration in minutes* | | **cardioFrequencyPerWeek** | Integer | | | *Recommended cardio sessions per week* | | **cardioType** | String | | | *Type of cardio recommended (e.g. zone2)* | | **dailyStepTarget** | Integer | | | *Daily step target for NEAT (7000-12000)* | | **deloadIntervalWeeks** | Integer | | | *Weeks between deload periods, typically 6-8* | | **notes** | Text | | | *Additional AI-generated notes and guidance* | | **splitType** | String | | | *Training split type (e.g. fullBody, upperLower, pushPullLegs)* | | **status** | Enum | | | *Program status* | | **userId** | ID | | | *Reference to the user who owns this training program* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Property Definition* : Program status*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **archived** | `"archived""` | 1 | ### UserQuota resource *Resource Definition* : Per-user message quota consumption tracking against the system-wide quota configuration. *UserQuota Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **messageCount** | Integer | | | *Number of messages consumed in the current period* | | **periodEnd** | Date | | | *End of the current quota period* | | **periodStart** | Date | | | *Start of the current quota period* | | **userId** | ID | | | *Reference to the user whose quota is being tracked* | ### WeightLog resource *Resource Definition* : User-reported weight measurements used for weekly average calculations and dynamic calorie adjustments by the AI coach. *WeightLog Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **measuredAt** | Date | | | *Date and time of measurement* | | **userId** | ID | | | *Reference to the user who recorded this weight* | | **weightKg** | Float | | | *Body weight in kilograms* | ### BanAppeals resource *BanAppeals Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **moderationRecordId** | ID | | | *id of the mod record* | | **userId** | ID | | | ** | | **appealReason** | String | | | ** | | **status** | Enum | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ### AdditionalQuota resource *AdditionalQuota Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **userId** | String | | | ** | | **additionalMessage** | Integer | | | ** | | **status** | Enum | | | ** | | **currency** | String | | | ** | | **pricePaid** | Integer | | | ** | | **statusUpdatedAt** | Date | | | ** | | **activatedAt** | Date | | | ** | | **cancelledAt** | Date | | | ** | | **periodEnd** | Date | | | ** | | **periodStart** | Date | | | ** | | **paymentConfirmation** | Enum | | | *An automatic property that is used to check the confirmed status of the payment set by webhooks.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **cancelled** | `"cancelled""` | 1 | | **failed** | `"failed""` | 2 | | **active** | `"active""` | 3 | | **expired** | `"expired""` | 4 | ##### paymentConfirmation Enum Property *Property Definition* : An automatic property that is used to check the confirmed status of the payment set by webhooks.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **processing** | `"processing""` | 1 | | **paid** | `"paid""` | 2 | | **canceled** | `"canceled""` | 3 | ### Sys_additionalQuotaPayment resource *Resource Definition* : A payment storage object to store the payment life cyle of orders based on additionalQuota object. It is autocreated based on the source object's checkout config *Sys_additionalQuotaPayment Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **ownerId** | ID | | | * An ID value to represent owner user who created the order* | | **orderId** | ID | | | *an ID value to represent the orderId which is the ID parameter of the source additionalQuota object* | | **paymentId** | String | | | *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 | | | *A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.* | | **statusLiteral** | String | | | *A string value to represent the logical payment status which belongs to the application lifecycle itself.* | | **redirectUrl** | String | | | *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.* | ### Sys_paymentCustomer resource *Resource Definition* : A payment storage object to store the customer values of the payment platform *Sys_paymentCustomer Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **userId** | ID | | | * An ID value to represent the user who is created as a stripe customer* | | **customerId** | String | | | *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 | | | *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.* | ### Sys_paymentMethod resource *Resource Definition* : A payment storage object to store the payment methods of the platform customers *Sys_paymentMethod Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **paymentMethodId** | String | | | *A string value to represent the id of the payment method on the payment platform.* | | **userId** | ID | | | * An ID value to represent the user who owns the payment method* | | **customerId** | String | | | *A string value to represent the customer id which is generated on the payment gateway.* | | **cardHolderName** | String | | | *A string value to represent the name of the card holder. It can be different than the registered customer.* | | **cardHolderZip** | String | | | *A string value to represent the zip code of the card holder. It is used for address verification in specific countries.* | | **platform** | String | | | *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 | | | *A Json value to store the card details of the payment method.* | ## Business Api ### `Create Chatmessage` API **[Default create API]** — This is the designated default `create` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send a message to the AI fitness coach. Enforces the full validation chain: subscription check → ban status check → quota check → content flagging → AI processing → tool call execution → quota increment. Returns both the user message and the AI response. **API Frontend Description By The Backend Architect** # Chat Message Creation - This is the primary interaction endpoint for the AI fitness coach. - User sends a message and receives an AI response in the same call. - The response includes the created user message and an aiResponse object containing the AI's reply and any tool calls executed. - If the message is flagged, aiResponse.flagged will be true. - Handle quota exceeded (403) and suspension (403) errors gracefully. **Rest Route** The `createChatMessage` API REST controller can be triggered via the following route: `/v1/chatmessages` **Rest Request Parameters** The `createChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.body?.["conversationId"] | | content | Text | true | request.body?.["content"] | **conversationId** : The conversation to send the message to **content** : The message content **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/chatmessages** ```js axios({ method: 'POST', url: '/v1/chatmessages', data: { conversationId:"ID", content:"Text", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Coachconversation` API **[Default create API]** — This is the designated default `create` API for the `coachConversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new coach conversation. Requires active subscription and no active ban. **Rest Route** The `createCoachConversation` API REST controller can be triggered via the following route: `/v1/coachconversations` **Rest Request Parameters** The `createCoachConversation` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coachconversations** ```js axios({ method: 'POST', url: '/v1/coachconversations', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coachConversation": { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "activeSubscriptions": "Object" } ``` ### `Create Quotaconfig` API **[Default create API]** — This is the designated default `create` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a quota configuration record. Admin only. **Rest Route** The `createQuotaConfig` API REST controller can be triggered via the following route: `/v1/quotaconfigs` **Rest Request Parameters** The `createQuotaConfig` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaLimit | Integer | true | request.body?.["quotaLimit"] | | quotaPeriod | Enum | true | request.body?.["quotaPeriod"] | **quotaLimit** : Maximum messages allowed per period **quotaPeriod** : Period over which the quota is measured **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/quotaconfigs** ```js axios({ method: 'POST', url: '/v1/quotaconfigs', data: { quotaLimit:"Integer", quotaPeriod:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Weightlog` API **[Default create API]** — This is the designated default `create` API for the `weightLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Report a weight measurement. Requires active subscription and no active ban. **Rest Route** The `createWeightLog` API REST controller can be triggered via the following route: `/v1/weightlogs` **Rest Request Parameters** The `createWeightLog` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | measuredAt | Date | true | request.body?.["measuredAt"] | | weightKg | Float | true | request.body?.["weightKg"] | **measuredAt** : Date and time of measurement **weightKg** : Body weight in kilograms **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/weightlogs** ```js axios({ method: 'POST', url: '/v1/weightlogs', data: { measuredAt:"Date", weightKg:"Float", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLog", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "weightLog": { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Chatmessage` API **[Default get API]** — This is the designated default `get` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a chat message by ID with parent conversation ownership validation. **Rest Route** The `getChatMessage` API REST controller can be triggered via the following route: `/v1/chatmessages/:chatMessageId` **Rest Request Parameters** The `getChatMessage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | **chatMessageId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/chatmessages/:chatMessageId** ```js axios({ method: 'GET', url: `/v1/chatmessages/${chatMessageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coachconversation` API **[Default get API]** — This is the designated default `get` API for the `coachConversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a conversation by ID. Users see their own, admins can see any. **Rest Route** The `getCoachConversation` API REST controller can be triggered via the following route: `/v1/coachconversations/:coachConversationId` **Rest Request Parameters** The `getCoachConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coachConversationId | ID | true | request.params?.["coachConversationId"] | **coachConversationId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coachconversations/:coachConversationId** ```js axios({ method: 'GET', url: `/v1/coachconversations/${coachConversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coachConversation": { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Mealplan` API **[Default get API]** — This is the designated default `get` API for the `mealPlan` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a meal plan by ID with meals. Users see their own, admins can see any. **Rest Route** The `getMealPlan` API REST controller can be triggered via the following route: `/v1/mealplans/:mealPlanId` **Rest Request Parameters** The `getMealPlan` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.params?.["mealPlanId"] | **mealPlanId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/mealplans/:mealPlanId** ```js axios({ method: 'GET', url: `/v1/mealplans/${mealPlanId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlan", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "mealPlan": { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "meals": [ { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ] } } ``` ### `Get Moderationrecord` API **[Default get API]** — This is the designated default `get` API for the `moderationRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a moderation record by ID. Admin only. **Rest Route** The `getModerationRecord` API REST controller can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` **Rest Request Parameters** The `getModerationRecord` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | **moderationRecordId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'GET', url: `/v1/moderationrecords/${moderationRecordId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Get Myquota` API Get the current user's quota usage for the active period. **Rest Route** The `getMyQuota` API REST controller can be triggered via the following route: `/v1/my-quota` **Rest Request Parameters** The `getMyQuota` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/my-quota** ```js axios({ method: 'GET', url: '/v1/my-quota', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userQuota": { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Planmeal` API **[Default get API]** — This is the designated default `get` API for the `planMeal` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a plan meal by ID with parent ownership validation. **Rest Route** The `getPlanMeal` API REST controller can be triggered via the following route: `/v1/planmeals/:planMealId` **Rest Request Parameters** The `getPlanMeal` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | planMealId | ID | true | request.params?.["planMealId"] | **planMealId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/planmeals/:planMealId** ```js axios({ method: 'GET', url: `/v1/planmeals/${planMealId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "planMeal", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "planMeal": { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Programexercise` API **[Default get API]** — This is the designated default `get` API for the `programExercise` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a program exercise by ID with parent ownership validation. **Rest Route** The `getProgramExercise` API REST controller can be triggered via the following route: `/v1/programexercises/:programExerciseId` **Rest Request Parameters** The `getProgramExercise` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | programExerciseId | ID | true | request.params?.["programExerciseId"] | **programExerciseId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/programexercises/:programExerciseId** ```js axios({ method: 'GET', url: `/v1/programexercises/${programExerciseId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "programExercise", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "programExercise": { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Quotaconfig` API **[Default get API]** — This is the designated default `get` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a quota configuration record. **Rest Route** The `getQuotaConfig` API REST controller can be triggered via the following route: `/v1/quotaconfigs/:quotaConfigId` **Rest Request Parameters** The `getQuotaConfig` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaConfigId | ID | true | request.params?.["quotaConfigId"] | **quotaConfigId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/quotaconfigs/:quotaConfigId** ```js axios({ method: 'GET', url: `/v1/quotaconfigs/${quotaConfigId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Trainingprogram` API **[Default get API]** — This is the designated default `get` API for the `trainingProgram` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a training program by ID. Users see their own programs, admins can see any. **Rest Route** The `getTrainingProgram` API REST controller can be triggered via the following route: `/v1/trainingprograms/:trainingProgramId` **Rest Request Parameters** The `getTrainingProgram` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.params?.["trainingProgramId"] | **trainingProgramId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/trainingprograms/:trainingProgramId** ```js axios({ method: 'GET', url: `/v1/trainingprograms/${trainingProgramId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingProgram", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "trainingProgram": { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "exercises": [ { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ] } } ``` ### `Get Userquota` API **[Default get API]** — This is the designated default `get` API for the `userQuota` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a user quota record. Users see their own, admins can see any. **Rest Route** The `getUserQuota` API REST controller can be triggered via the following route: `/v1/userquotas/:userQuotaId` **Rest Request Parameters** The `getUserQuota` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userQuotaId | ID | true | request.params?.["userQuotaId"] | **userQuotaId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/userquotas/:userQuotaId** ```js axios({ method: 'GET', url: `/v1/userquotas/${userQuotaId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userQuota": { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "additionalQuota": "Object" } ``` ### `Get Weightlog` API **[Default get API]** — This is the designated default `get` API for the `weightLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a weight log entry by ID. **Rest Route** The `getWeightLog` API REST controller can be triggered via the following route: `/v1/weightlogs/:weightLogId` **Rest Request Parameters** The `getWeightLog` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | weightLogId | ID | true | request.params?.["weightLogId"] | **weightLogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/weightlogs/:weightLogId** ```js axios({ method: 'GET', url: `/v1/weightlogs/${weightLogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "weightLog": { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Chatmessages` API **[Default list API]** — This is the designated default `list` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List chat messages for a conversation with parent ownership validation. **Rest Route** The `listChatMessages` API REST controller can be triggered via the following route: `/v1/chatmessages` **Rest Request Parameters** The `listChatMessages` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.query?.["conversationId"] | **conversationId** : The conversation to list messages for **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/chatmessages** ```js axios({ method: 'GET', url: '/v1/chatmessages', data: { }, params: { conversationId:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "chatMessages": [ { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Coachconversations` API **[Default list API]** — This is the designated default `list` API for the `coachConversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List conversations. Users see their own, admins can see all. **Rest Route** The `listCoachConversations` API REST controller can be triggered via the following route: `/v1/coachconversations` **Rest Request Parameters** **Filter Parameters** The `listCoachConversations` api supports 2 optional filter parameters for filtering list results: **status** (`Enum`): Conversation status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this conversation - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coachconversations** ```js axios({ method: 'GET', url: '/v1/coachconversations', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coachConversations": [ { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Mealplans` API **[Default list API]** — This is the designated default `list` API for the `mealPlan` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List meal plans. Users see their own, admins can see all. **Rest Route** The `listMealPlans` API REST controller can be triggered via the following route: `/v1/mealplans` **Rest Request Parameters** **Filter Parameters** The `listMealPlans` api supports 2 optional filter parameters for filtering list results: **status** (`Enum`): Meal plan status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this meal plan - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/mealplans** ```js axios({ method: 'GET', url: '/v1/mealplans', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlans", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "mealPlans": [ { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Moderationrecords` API **[Default list API]** — This is the designated default `list` API for the `moderationRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moderation records. Admin only. Supports filtering by userId and action. **Rest Route** The `listModerationRecords` API REST controller can be triggered via the following route: `/v1/moderationrecords` **Rest Request Parameters** **Filter Parameters** The `listModerationRecords` api supports 2 optional filter parameters for filtering list results: **action** (`Enum`): Moderation action taken - Single: `?action=` (case-insensitive) - Multiple: `?action=&action=` - Null: `?action=null` **userId** (`ID`): Reference to the user who was moderated - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/moderationrecords** ```js axios({ method: 'GET', url: '/v1/moderationrecords', data: { }, params: { // Filter parameters (see Filter Parameters section above) // action: '' // Filter by action // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "moderationRecords": [ { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Planmeals` API **[Default list API]** — This is the designated default `list` API for the `planMeal` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List meals for a meal plan with parent ownership validation. **Rest Route** The `listPlanMeals` API REST controller can be triggered via the following route: `/v1/planmeals` **Rest Request Parameters** The `listPlanMeals` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.query?.["mealPlanId"] | **mealPlanId** : The meal plan ID to list meals for **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/planmeals** ```js axios({ method: 'GET', url: '/v1/planmeals', data: { }, params: { mealPlanId:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "planMeals", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "planMeals": [ { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Programexercises` API **[Default list API]** — This is the designated default `list` API for the `programExercise` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List exercises for a training program. Validates parent program ownership. **Rest Route** The `listProgramExercises` API REST controller can be triggered via the following route: `/v1/programexercises` **Rest Request Parameters** The `listProgramExercises` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.query?.["trainingProgramId"] | **trainingProgramId** : The training program ID to list exercises for **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/programexercises** ```js axios({ method: 'GET', url: '/v1/programexercises', data: { }, params: { trainingProgramId:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "programExercises", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "programExercises": [ { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Quotaconfigs` API **[Default list API]** — This is the designated default `list` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List quota configuration records. **Rest Route** The `listQuotaConfigs` API REST controller can be triggered via the following route: `/v1/quotaconfigs` **Rest Request Parameters** The `listQuotaConfigs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/quotaconfigs** ```js axios({ method: 'GET', url: '/v1/quotaconfigs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "quotaConfigs": [ { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Trainingprograms` API **[Default list API]** — This is the designated default `list` API for the `trainingProgram` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List training programs. Users see their own programs, admins can see all. **Rest Route** The `listTrainingPrograms` API REST controller can be triggered via the following route: `/v1/trainingprograms` **Rest Request Parameters** **Filter Parameters** The `listTrainingPrograms` api supports 2 optional filter parameters for filtering list results: **status** (`Enum`): Program status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this training program - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/trainingprograms** ```js axios({ method: 'GET', url: '/v1/trainingprograms', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingPrograms", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "trainingPrograms": [ { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Userquotas` API **[Default list API]** — This is the designated default `list` API for the `userQuota` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all user quotas. Admin only. **Rest Route** The `listUserQuotas` API REST controller can be triggered via the following route: `/v1/userquotas` **Rest Request Parameters** **Filter Parameters** The `listUserQuotas` api supports 1 optional filter parameter for filtering list results: **userId** (`ID`): Reference to the user whose quota is being tracked - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/userquotas** ```js axios({ method: 'GET', url: '/v1/userquotas', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuotas", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userQuotas": [ { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Weightlogs` API **[Default list API]** — This is the designated default `list` API for the `weightLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List weight log entries. Users see their own, admins see all. **Rest Route** The `listWeightLogs` API REST controller can be triggered via the following route: `/v1/weightlogs` **Rest Request Parameters** The `listWeightLogs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/weightlogs** ```js axios({ method: 'GET', url: '/v1/weightlogs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "weightLogs": [ { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Quotaconfig` API **[Default update API]** — This is the designated default `update` API for the `quotaConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a quota configuration record. Admin only. **Rest Route** The `updateQuotaConfig` API REST controller can be triggered via the following route: `/v1/quotaconfigs/:quotaConfigId` **Rest Request Parameters** The `updateQuotaConfig` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaConfigId | ID | true | request.params?.["quotaConfigId"] | | quotaLimit | Integer | false | request.body?.["quotaLimit"] | | quotaPeriod | Enum | false | request.body?.["quotaPeriod"] | **quotaConfigId** : This id paremeter is used to select the required data object that will be updated **quotaLimit** : Maximum messages allowed per period **quotaPeriod** : Period over which the quota is measured **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/quotaconfigs/:quotaConfigId** ```js axios({ method: 'PATCH', url: `/v1/quotaconfigs/${quotaConfigId}`, data: { quotaLimit:"Integer", quotaPeriod:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Moderationrecord` API **Rest Route** The `deleteModerationRecord` API REST controller can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` **Rest Request Parameters** The `deleteModerationRecord` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | **moderationRecordId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'DELETE', url: `/v1/moderationrecords/${moderationRecordId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `Do Deletemealplan` API **Rest Route** The `deletemealplan` API REST controller can be triggered via the following route: `/v1/deletemealplan/:mealPlanId` **Rest Request Parameters** The `deletemealplan` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.params?.["mealPlanId"] | **mealPlanId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/deletemealplan/:mealPlanId** ```js axios({ method: 'DELETE', url: `/v1/deletemealplan/${mealPlanId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlan", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "mealPlan": { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Do Deletetrainingprogram` API **Rest Route** The `deletetrainingprogram` API REST controller can be triggered via the following route: `/v1/deletetrainingprogram/:trainingProgramId` **Rest Request Parameters** The `deletetrainingprogram` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.params?.["trainingProgramId"] | **trainingProgramId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/deletetrainingprogram/:trainingProgramId** ```js axios({ method: 'DELETE', url: `/v1/deletetrainingprogram/${trainingProgramId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingProgram", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "trainingProgram": { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Moderationrecord` API **Rest Route** The `updateModerationRecord` API REST controller can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` **Rest Request Parameters** The `updateModerationRecord` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | | action | String | true | request.body?.["action"] | | content | String | false | request.body?.["content"] | **moderationRecordId** : This id paremeter is used to select the required data object that will be updated **action** : **content** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'PATCH', url: `/v1/moderationrecords/${moderationRecordId}`, data: { action:"String", content:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Do Listmymoderationrecords` API **Rest Route** The `listmymoderationrecords` API REST controller can be triggered via the following route: `/v1/listmymoderationrecords` **Rest Request Parameters** **Filter Parameters** The `listmymoderationrecords` api supports 1 optional filter parameter for filtering list results: **action** (`Enum`): Moderation action taken - Single: `?action=` (case-insensitive) - Multiple: `?action=&action=` - Null: `?action=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/listmymoderationrecords** ```js axios({ method: 'GET', url: '/v1/listmymoderationrecords', data: { }, params: { // Filter parameters (see Filter Parameters section above) // action: '' // Filter by action } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "moderationRecords": [ { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Banappeals` API **Rest Route** The `listBanAppeals` API REST controller can be triggered via the following route: `/v1/banappealses` **Rest Request Parameters** The `listBanAppeals` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | false | request.query?.["userId"] | | status | ID | false | request.query?.["status"] | **userId** : **status** : **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/banappealses** ```js axios({ method: 'GET', url: '/v1/banappealses', data: { }, params: { userId:'"ID"', status:'"ID"', } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppealses", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "banAppealses": [ { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "showmoderationRecord": [ { "offenseType": "String", "reason": "Text", "userId": "ID", "content": "String" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Banappeal` API **Rest Route** The `createBanAppeal` API REST controller can be triggered via the following route: `/v1/banappeal` **Rest Request Parameters** The `createBanAppeal` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.body?.["moderationRecordId"] | | appealReason | String | true | request.body?.["appealReason"] | | status | Enum | true | request.body?.["status"] | **moderationRecordId** : id of the mod record **appealReason** : **status** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/banappeal** ```js axios({ method: 'POST', url: '/v1/banappeal', data: { moderationRecordId:"ID", appealReason:"String", status:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppeals", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "banAppeals": { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Banappeal` API **Rest Route** The `updateBanAppeal` API REST controller can be triggered via the following route: `/v1/banappeal/:banAppealsId` **Rest Request Parameters** The `updateBanAppeal` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | banAppealsId | ID | true | request.params?.["banAppealsId"] | | status | Enum | true | request.body?.["status"] | | moderationRecordId | ID | false | request.body?.["moderationRecordId"] | | appealReason | String | false | request.body?.["appealReason"] | **banAppealsId** : This id paremeter is used to select the required data object that will be updated **status** : **moderationRecordId** : id of the mod record **appealReason** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/banappeal/:banAppealsId** ```js axios({ method: 'PATCH', url: `/v1/banappeal/${banAppealsId}`, data: { status:"Enum", moderationRecordId:"ID", appealReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppeals", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "banAppeals": { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Additionalquota` API **Rest Route** The `createAdditionalQuota` API REST controller can be triggered via the following route: `/v1/additionalquotas` **Rest Request Parameters** The `createAdditionalQuota` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalMessage | Integer | true | request.body?.["additionalMessage"] | | status | Enum | true | request.body?.["status"] | | currency | String | true | request.body?.["currency"] | | pricePaid | Integer | true | request.body?.["pricePaid"] | | statusUpdatedAt | Date | false | request.body?.["statusUpdatedAt"] | | activatedAt | Date | false | request.body?.["activatedAt"] | | cancelledAt | Date | false | request.body?.["cancelledAt"] | | periodEnd | Date | false | request.body?.["periodEnd"] | | periodStart | Date | false | request.body?.["periodStart"] | **additionalMessage** : **status** : **currency** : **pricePaid** : **statusUpdatedAt** : **activatedAt** : **cancelledAt** : **periodEnd** : **periodStart** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/additionalquotas** ```js axios({ method: 'POST', url: '/v1/additionalquotas', data: { additionalMessage:"Integer", status:"Enum", currency:"String", pricePaid:"Integer", statusUpdatedAt:"Date", activatedAt:"Date", cancelledAt:"Date", periodEnd:"Date", periodStart:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Myadditionalquota` API **Rest Route** The `getMyAdditionalQuota` API REST controller can be triggered via the following route: `/v1/myadditionalquota` **Rest Request Parameters** The `getMyAdditionalQuota` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myadditionalquota** ```js axios({ method: 'GET', url: '/v1/myadditionalquota', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "myaddQuota": "Object" } ``` ### `Get Additionalquotapayment` API This route is used to get the payment information by ID. **Rest Route** The `getAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` **Rest Request Parameters** The `getAdditionalQuotaPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | **sys_additionalQuotaPaymentId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'GET', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Additionalquotapayments` API This route is used to list all payments. **Rest Route** The `listAdditionalQuotaPayments` API REST controller can be triggered via the following route: `/v1/additionalquotapayments` **Rest Request Parameters** **Filter Parameters** The `listAdditionalQuotaPayments` api supports 6 optional filter parameters for filtering list results: **ownerId** (`ID`): An ID value to represent owner user who created the order - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source additionalQuota object - Single: `?orderId=` - Multiple: `?orderId=&orderId=` - Null: `?orderId=null` **paymentId** (`String`): 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 - Single (partial match, case-insensitive): `?paymentId=` - Multiple: `?paymentId=&paymentId=` - Null: `?paymentId=null` **paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. - Single (partial match, case-insensitive): `?paymentStatus=` - Multiple: `?paymentStatus=&paymentStatus=` - Null: `?paymentStatus=null` **statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself. - Single (partial match, case-insensitive): `?statusLiteral=` - Multiple: `?statusLiteral=&statusLiteral=` - Null: `?statusLiteral=null` **redirectUrl** (`String`): 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. - Single (partial match, case-insensitive): `?redirectUrl=` - Multiple: `?redirectUrl=&redirectUrl=` - Null: `?redirectUrl=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalquotapayments** ```js axios({ method: 'GET', url: '/v1/additionalquotapayments', data: { }, params: { // Filter parameters (see Filter Parameters section above) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_additionalQuotaPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Additionalquotapayment` API This route is used to create a new payment. **Rest Route** The `createAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment` **Rest Request Parameters** The `createAdditionalQuotaPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source additionalQuota object **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/additionalquotapayment** ```js axios({ method: 'POST', url: '/v1/additionalquotapayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Additionalquotapayment` API This route is used to update an existing payment. **Rest Route** The `updateAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` **Rest Request Parameters** The `updateAdditionalQuotaPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **sys_additionalQuotaPaymentId** : This id paremeter is used to select the required data object that will be updated **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'PATCH', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Additionalquotapayment` API This route is used to delete a payment. **Rest Route** The `deleteAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` **Rest Request Parameters** The `deleteAdditionalQuotaPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | **sys_additionalQuotaPaymentId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'DELETE', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Additionalquotapaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getAdditionalQuotaPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/additionalQuotapaymentbyorderid/:orderId` **Rest Request Parameters** The `getAdditionalQuotaPaymentByOrderId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source additionalQuota object. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalQuotapaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/additionalQuotapaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Additionalquotapaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getAdditionalQuotaPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/additionalQuotapaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getAdditionalQuotaPaymentByPaymentId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | **paymentId** : 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. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/additionalQuotapaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/additionalQuotapaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Start Additionalquotapayment` API Start payment for additionalQuota **Rest Route** The `startAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/startadditionalquotapayment/:additionalQuotaId` **Rest Request Parameters** The `startAdditionalQuotaPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **additionalQuotaId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/startadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Refresh Additionalquotapayment` API Refresh payment info for additionalQuota from Stripe **Rest Route** The `refreshAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/refreshadditionalquotapayment/:additionalQuotaId` **Rest Request Parameters** The `refreshAdditionalQuotaPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **additionalQuotaId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to refresh a stripe payment process **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refreshadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/refreshadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Callback Additionalquotapayment` API Refresh payment values by gateway webhook call for additionalQuota **Rest Route** The `callbackAdditionalQuotaPayment` API REST controller can be triggered via the following route: `/v1/callbackadditionalquotapayment` **Rest Request Parameters** The `callbackAdditionalQuotaPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | false | request.body?.["additionalQuotaId"] | **additionalQuotaId** : The order id parameter that will be read from webhook callback params **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/callbackadditionalquotapayment** ```js axios({ method: 'POST', url: '/v1/callbackadditionalquotapayment', data: { additionalQuotaId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Get Paymentcustomerbyuserid` API This route is used to get the payment customer information by user id. **Rest Route** The `getPaymentCustomerByUserId` API REST controller can be triggered via the following route: `/v1/paymentcustomers/:userId` **Rest Request Parameters** The `getPaymentCustomerByUserId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Paymentcustomers` API This route is used to list all payment customers. **Rest Route** The `listPaymentCustomers` API REST controller can be triggered via the following route: `/v1/paymentcustomers` **Rest Request Parameters** **Filter Parameters** The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results: **userId** (`ID`): An ID value to represent the user who is created as a stripe customer - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **customerId** (`String`): 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 - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Paymentcustomermethods` API This route is used to list all payment customer methods. **Rest Route** The `listPaymentCustomerMethods` API REST controller can be triggered via the following route: `/v1/paymentcustomermethods/:userId` **Rest Request Parameters** The `listPaymentCustomerMethods` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who owns the payment method. The parameter is used to query data. **Filter Parameters** The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results: **paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform. - Single (partial match, case-insensitive): `?paymentMethodId=` - Multiple: `?paymentMethodId=&paymentMethodId=` - Null: `?paymentMethodId=null` **customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway. - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer. - Single (partial match, case-insensitive): `?cardHolderName=` - Multiple: `?cardHolderName=&cardHolderName=` - Null: `?cardHolderName=null` **cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries. - Single (partial match, case-insensitive): `?cardHolderZip=` - Multiple: `?cardHolderZip=&cardHolderZip=` - Null: `?cardHolderZip=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **cardInfo** (`Object`): A Json value to store the card details of the payment method. - Single: `?cardInfo=` - Multiple: `?cardInfo=&cardInfo=` - Null: `?cardInfo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- ## EVENT GUIDE # EVENT GUIDE ## aifitapp-aicoach-service 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 ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. # Documentation Scope Welcome to the official documentation for the `AiCoach` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `AiCoach` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `AiCoach` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `AiCoach` objects. **Overview** This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples. # Authentication and Authorization Access to the `AiCoach` service's events is facilitated through the project's Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server. Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide. # Database Events Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic. Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service's scope, ensuring data consistency and syncronization across services. For example, while a business operation such as "approve membership" might generate a high-level business event like `membership-approved`, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as `dbevent-member-updated` and `dbevent-user-updated`, reflecting the granular changes at the database level. Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes. ## DbEvent chatMessage-created **Event topic**: `appaili-aicoach-service-dbevent-chatmessage-created` This event is triggered upon the creation of a `chatMessage` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent chatMessage-updated **Event topic**: `appaili-aicoach-service-dbevent-chatmessage-updated` Activation of this event follows the update of a `chatMessage` data object. The payload contains the updated information under the `chatMessage` attribute, along with the original data prior to update, labeled as `old_chatMessage` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_chatMessage:{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, chatMessage:{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent chatMessage-deleted **Event topic**: `appaili-aicoach-service-dbevent-chatmessage-deleted` This event announces the deletion of a `chatMessage` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent coachConversation-created **Event topic**: `appaili-aicoach-service-dbevent-coachconversation-created` This event is triggered upon the creation of a `coachConversation` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent coachConversation-updated **Event topic**: `appaili-aicoach-service-dbevent-coachconversation-updated` Activation of this event follows the update of a `coachConversation` data object. The payload contains the updated information under the `coachConversation` attribute, along with the original data prior to update, labeled as `old_coachConversation` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_coachConversation:{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, coachConversation:{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent coachConversation-deleted **Event topic**: `appaili-aicoach-service-dbevent-coachconversation-deleted` This event announces the deletion of a `coachConversation` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent mealPlan-created **Event topic**: `appaili-aicoach-service-dbevent-mealplan-created` This event is triggered upon the creation of a `mealPlan` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent mealPlan-updated **Event topic**: `appaili-aicoach-service-dbevent-mealplan-updated` Activation of this event follows the update of a `mealPlan` data object. The payload contains the updated information under the `mealPlan` attribute, along with the original data prior to update, labeled as `old_mealPlan` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_mealPlan:{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, mealPlan:{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent mealPlan-deleted **Event topic**: `appaili-aicoach-service-dbevent-mealplan-deleted` This event announces the deletion of a `mealPlan` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent moderationRecord-created **Event topic**: `appaili-aicoach-service-dbevent-moderationrecord-created` This event is triggered upon the creation of a `moderationRecord` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent moderationRecord-updated **Event topic**: `appaili-aicoach-service-dbevent-moderationrecord-updated` Activation of this event follows the update of a `moderationRecord` data object. The payload contains the updated information under the `moderationRecord` attribute, along with the original data prior to update, labeled as `old_moderationRecord` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_moderationRecord:{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, moderationRecord:{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent moderationRecord-deleted **Event topic**: `appaili-aicoach-service-dbevent-moderationrecord-deleted` This event announces the deletion of a `moderationRecord` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false} ``` ## DbEvent planMeal-created **Event topic**: `appaili-aicoach-service-dbevent-planmeal-created` This event is triggered upon the creation of a `planMeal` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent planMeal-updated **Event topic**: `appaili-aicoach-service-dbevent-planmeal-updated` Activation of this event follows the update of a `planMeal` data object. The payload contains the updated information under the `planMeal` attribute, along with the original data prior to update, labeled as `old_planMeal` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_planMeal:{"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, planMeal:{"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent planMeal-deleted **Event topic**: `appaili-aicoach-service-dbevent-planmeal-deleted` This event announces the deletion of a `planMeal` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent programExercise-created **Event topic**: `appaili-aicoach-service-dbevent-programexercise-created` This event is triggered upon the creation of a `programExercise` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent programExercise-updated **Event topic**: `appaili-aicoach-service-dbevent-programexercise-updated` Activation of this event follows the update of a `programExercise` data object. The payload contains the updated information under the `programExercise` attribute, along with the original data prior to update, labeled as `old_programExercise` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_programExercise:{"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, programExercise:{"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent programExercise-deleted **Event topic**: `appaili-aicoach-service-dbevent-programexercise-deleted` This event announces the deletion of a `programExercise` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent quotaConfig-created **Event topic**: `appaili-aicoach-service-dbevent-quotaconfig-created` This event is triggered upon the creation of a `quotaConfig` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent quotaConfig-updated **Event topic**: `appaili-aicoach-service-dbevent-quotaconfig-updated` Activation of this event follows the update of a `quotaConfig` data object. The payload contains the updated information under the `quotaConfig` attribute, along with the original data prior to update, labeled as `old_quotaConfig` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_quotaConfig:{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, quotaConfig:{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent quotaConfig-deleted **Event topic**: `appaili-aicoach-service-dbevent-quotaconfig-deleted` This event announces the deletion of a `quotaConfig` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent trainingProgram-created **Event topic**: `appaili-aicoach-service-dbevent-trainingprogram-created` This event is triggered upon the creation of a `trainingProgram` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent trainingProgram-updated **Event topic**: `appaili-aicoach-service-dbevent-trainingprogram-updated` Activation of this event follows the update of a `trainingProgram` data object. The payload contains the updated information under the `trainingProgram` attribute, along with the original data prior to update, labeled as `old_trainingProgram` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_trainingProgram:{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, trainingProgram:{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent trainingProgram-deleted **Event topic**: `appaili-aicoach-service-dbevent-trainingprogram-deleted` This event announces the deletion of a `trainingProgram` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent userQuota-created **Event topic**: `appaili-aicoach-service-dbevent-userquota-created` This event is triggered upon the creation of a `userQuota` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent userQuota-updated **Event topic**: `appaili-aicoach-service-dbevent-userquota-updated` Activation of this event follows the update of a `userQuota` data object. The payload contains the updated information under the `userQuota` attribute, along with the original data prior to update, labeled as `old_userQuota` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_userQuota:{"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, userQuota:{"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent userQuota-deleted **Event topic**: `appaili-aicoach-service-dbevent-userquota-deleted` This event announces the deletion of a `userQuota` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent weightLog-created **Event topic**: `appaili-aicoach-service-dbevent-weightlog-created` This event is triggered upon the creation of a `weightLog` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent weightLog-updated **Event topic**: `appaili-aicoach-service-dbevent-weightlog-updated` Activation of this event follows the update of a `weightLog` data object. The payload contains the updated information under the `weightLog` attribute, along with the original data prior to update, labeled as `old_weightLog` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_weightLog:{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, weightLog:{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent weightLog-deleted **Event topic**: `appaili-aicoach-service-dbevent-weightlog-deleted` This event announces the deletion of a `weightLog` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent banAppeals-created **Event topic**: `appaili-aicoach-service-dbevent-banappeals-created` This event is triggered upon the creation of a `banAppeals` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent banAppeals-updated **Event topic**: `appaili-aicoach-service-dbevent-banappeals-updated` Activation of this event follows the update of a `banAppeals` data object. The payload contains the updated information under the `banAppeals` attribute, along with the original data prior to update, labeled as `old_banAppeals` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_banAppeals:{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, banAppeals:{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent banAppeals-deleted **Event topic**: `appaili-aicoach-service-dbevent-banappeals-deleted` This event announces the deletion of a `banAppeals` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent additionalQuota-created **Event topic**: `appaili-aicoach-service-dbevent-additionalquota-created` This event is triggered upon the creation of a `additionalQuota` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent additionalQuota-updated **Event topic**: `appaili-aicoach-service-dbevent-additionalquota-updated` Activation of this event follows the update of a `additionalQuota` data object. The payload contains the updated information under the `additionalQuota` attribute, along with the original data prior to update, labeled as `old_additionalQuota` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_additionalQuota:{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, additionalQuota:{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent additionalQuota-deleted **Event topic**: `appaili-aicoach-service-dbevent-additionalquota-deleted` This event announces the deletion of a `additionalQuota` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_additionalQuotaPayment-created **Event topic**: `appaili-aicoach-service-dbevent-sys_additionalquotapayment-created` This event is triggered upon the creation of a `sys_additionalQuotaPayment` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_additionalQuotaPayment-updated **Event topic**: `appaili-aicoach-service-dbevent-sys_additionalquotapayment-updated` Activation of this event follows the update of a `sys_additionalQuotaPayment` data object. The payload contains the updated information under the `sys_additionalQuotaPayment` attribute, along with the original data prior to update, labeled as `old_sys_additionalQuotaPayment` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_additionalQuotaPayment:{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_additionalQuotaPayment:{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_additionalQuotaPayment-deleted **Event topic**: `appaili-aicoach-service-dbevent-sys_additionalquotapayment-deleted` This event announces the deletion of a `sys_additionalQuotaPayment` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentCustomer-created **Event topic**: `appaili-aicoach-service-dbevent-sys_paymentcustomer-created` This event is triggered upon the creation of a `sys_paymentCustomer` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentCustomer-updated **Event topic**: `appaili-aicoach-service-dbevent-sys_paymentcustomer-updated` Activation of this event follows the update of a `sys_paymentCustomer` data object. The payload contains the updated information under the `sys_paymentCustomer` attribute, along with the original data prior to update, labeled as `old_sys_paymentCustomer` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_paymentCustomer:{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_paymentCustomer:{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_paymentCustomer-deleted **Event topic**: `appaili-aicoach-service-dbevent-sys_paymentcustomer-deleted` This event announces the deletion of a `sys_paymentCustomer` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentMethod-created **Event topic**: `appaili-aicoach-service-dbevent-sys_paymentmethod-created` This event is triggered upon the creation of a `sys_paymentMethod` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentMethod-updated **Event topic**: `appaili-aicoach-service-dbevent-sys_paymentmethod-updated` Activation of this event follows the update of a `sys_paymentMethod` data object. The payload contains the updated information under the `sys_paymentMethod` attribute, along with the original data prior to update, labeled as `old_sys_paymentMethod` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_paymentMethod:{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_paymentMethod:{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_paymentMethod-deleted **Event topic**: `appaili-aicoach-service-dbevent-sys_paymentmethod-deleted` This event announces the deletion of a `sys_paymentMethod` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` # ElasticSearch Index Events Within the `AiCoach` service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects. These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries. It's noteworthy that some services may augment another service's index by appending to the entity’s `extends` object. In such scenarios, an `*-extended` event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID. This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications. ## Index Event chatmessage-created **Event topic**: `elastic-index-aifitapp_chatmessage-created` **Event payload**: ```json {"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmessage-updated **Event topic**: `elastic-index-aifitapp_chatmessage-created` **Event payload**: ```json {"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmessage-deleted **Event topic**: `elastic-index-aifitapp_chatmessage-deleted` **Event payload**: ```json {"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmessage-extended **Event topic**: `elastic-index-aifitapp_chatmessage-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event coachconversation-created **Event topic**: `elastic-index-aifitapp_coachconversation-created` **Event payload**: ```json {"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coachconversation-updated **Event topic**: `elastic-index-aifitapp_coachconversation-created` **Event payload**: ```json {"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coachconversation-deleted **Event topic**: `elastic-index-aifitapp_coachconversation-deleted` **Event payload**: ```json {"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coachconversation-extended **Event topic**: `elastic-index-aifitapp_coachconversation-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event mealplan-created **Event topic**: `elastic-index-aifitapp_mealplan-created` **Event payload**: ```json {"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event mealplan-updated **Event topic**: `elastic-index-aifitapp_mealplan-created` **Event payload**: ```json {"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event mealplan-deleted **Event topic**: `elastic-index-aifitapp_mealplan-deleted` **Event payload**: ```json {"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event mealplan-extended **Event topic**: `elastic-index-aifitapp_mealplan-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event moderationrecord-created **Event topic**: `elastic-index-aifitapp_moderationrecord-created` **Event payload**: ```json {"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event moderationrecord-updated **Event topic**: `elastic-index-aifitapp_moderationrecord-created` **Event payload**: ```json {"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event moderationrecord-deleted **Event topic**: `elastic-index-aifitapp_moderationrecord-deleted` **Event payload**: ```json {"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event moderationrecord-extended **Event topic**: `elastic-index-aifitapp_moderationrecord-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event planmeal-created **Event topic**: `elastic-index-aifitapp_planmeal-created` **Event payload**: ```json {"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event planmeal-updated **Event topic**: `elastic-index-aifitapp_planmeal-created` **Event payload**: ```json {"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event planmeal-deleted **Event topic**: `elastic-index-aifitapp_planmeal-deleted` **Event payload**: ```json {"id":"ID","carbs":"Float","fat":"Float","foods":"Text","mealLabel":"String","mealPlanId":"ID","protein":"Float","sortOrder":"Integer","totalCalories":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event planmeal-extended **Event topic**: `elastic-index-aifitapp_planmeal-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event programexercise-created **Event topic**: `elastic-index-aifitapp_programexercise-created` **Event payload**: ```json {"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event programexercise-updated **Event topic**: `elastic-index-aifitapp_programexercise-created` **Event payload**: ```json {"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event programexercise-deleted **Event topic**: `elastic-index-aifitapp_programexercise-deleted` **Event payload**: ```json {"id":"ID","dayLabel":"String","exerciseName":"String","movementType":"Enum","movementType_idx":"Integer","muscleGroup":"String","progressionRule":"Text","repMax":"Integer","repMin":"Integer","rirTarget":"Integer","sets":"Integer","sortOrder":"Integer","trainingProgramId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event programexercise-extended **Event topic**: `elastic-index-aifitapp_programexercise-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event quotaconfig-created **Event topic**: `elastic-index-aifitapp_quotaconfig-created` **Event payload**: ```json {"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event quotaconfig-updated **Event topic**: `elastic-index-aifitapp_quotaconfig-created` **Event payload**: ```json {"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event quotaconfig-deleted **Event topic**: `elastic-index-aifitapp_quotaconfig-deleted` **Event payload**: ```json {"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event quotaconfig-extended **Event topic**: `elastic-index-aifitapp_quotaconfig-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event trainingprogram-created **Event topic**: `elastic-index-aifitapp_trainingprogram-created` **Event payload**: ```json {"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event trainingprogram-updated **Event topic**: `elastic-index-aifitapp_trainingprogram-created` **Event payload**: ```json {"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event trainingprogram-deleted **Event topic**: `elastic-index-aifitapp_trainingprogram-deleted` **Event payload**: ```json {"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event trainingprogram-extended **Event topic**: `elastic-index-aifitapp_trainingprogram-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event userquota-created **Event topic**: `elastic-index-aifitapp_userquota-created` **Event payload**: ```json {"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event userquota-updated **Event topic**: `elastic-index-aifitapp_userquota-created` **Event payload**: ```json {"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event userquota-deleted **Event topic**: `elastic-index-aifitapp_userquota-deleted` **Event payload**: ```json {"id":"ID","messageCount":"Integer","periodEnd":"Date","periodStart":"Date","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event userquota-extended **Event topic**: `elastic-index-aifitapp_userquota-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event weightlog-created **Event topic**: `elastic-index-aifitapp_weightlog-created` **Event payload**: ```json {"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event weightlog-updated **Event topic**: `elastic-index-aifitapp_weightlog-created` **Event payload**: ```json {"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event weightlog-deleted **Event topic**: `elastic-index-aifitapp_weightlog-deleted` **Event payload**: ```json {"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event weightlog-extended **Event topic**: `elastic-index-aifitapp_weightlog-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event banappeals-created **Event topic**: `elastic-index-aifitapp_banappeals-created` **Event payload**: ```json {"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event banappeals-updated **Event topic**: `elastic-index-aifitapp_banappeals-created` **Event payload**: ```json {"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event banappeals-deleted **Event topic**: `elastic-index-aifitapp_banappeals-deleted` **Event payload**: ```json {"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event banappeals-extended **Event topic**: `elastic-index-aifitapp_banappeals-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event additionalquota-created **Event topic**: `elastic-index-aifitapp_additionalquota-created` **Event payload**: ```json {"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event additionalquota-updated **Event topic**: `elastic-index-aifitapp_additionalquota-created` **Event payload**: ```json {"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event additionalquota-deleted **Event topic**: `elastic-index-aifitapp_additionalquota-deleted` **Event payload**: ```json {"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event additionalquota-extended **Event topic**: `elastic-index-aifitapp_additionalquota-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event sys_additionalquotapayment-created **Event topic**: `elastic-index-aifitapp_sys_additionalquotapayment-created` **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_additionalquotapayment-updated **Event topic**: `elastic-index-aifitapp_sys_additionalquotapayment-created` **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_additionalquotapayment-deleted **Event topic**: `elastic-index-aifitapp_sys_additionalquotapayment-deleted` **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_additionalquotapayment-extended **Event topic**: `elastic-index-aifitapp_sys_additionalquotapayment-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event sys_paymentcustomer-created **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-created` **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentcustomer-updated **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-created` **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentcustomer-deleted **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-deleted` **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentcustomer-extended **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event sys_paymentmethod-created **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-created` **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentmethod-updated **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-created` **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentmethod-deleted **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-deleted` **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentmethod-extended **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event chatmessage-created **Event topic** : `appaili-aicoach-service-chatmessage-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `chatMessage` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`chatMessage`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","content":"Text","conversationId":"ID","flagged":"Boolean","role":"Enum","role_idx":"Integer","toolCallData":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coachconversation-created **Event topic** : `appaili-aicoach-service-coachconversation-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `coachConversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coachConversation`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coachConversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coachConversation":{"id":"ID","status":"Enum","status_idx":"Integer","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"activeSubscriptions":"Object"} ``` ## Route Event quotaconfig-created **Event topic** : `appaili-aicoach-service-quotaconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event weightlog-created **Event topic** : `appaili-aicoach-service-weightlog-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `weightLog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`weightLog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"weightLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"weightLog":{"id":"ID","measuredAt":"Date","userId":"ID","weightKg":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event quotaconfig-updated **Event topic** : `appaili-aicoach-service-quotaconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `quotaConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`quotaConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"quotaConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"quotaConfig":{"id":"ID","quotaLimit":"Integer","quotaPeriod":"Enum","quotaPeriod_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-deleted **Event topic** : `appaili-aicoach-service-moderationrecord-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event deletemealplan-done **Event topic** : `appaili-aicoach-service-deletemealplan-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `mealPlan` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`mealPlan`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"mealPlan","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"mealPlan":{"id":"ID","carbGrams":"Float","dailyCalorieTarget":"Integer","fatGrams":"Float","notes":"Text","proteinGrams":"Float","restDayCalories":"Integer","restDayCarbGrams":"Float","status":"Enum","status_idx":"Integer","trainingDayCalories":"Integer","trainingDayCarbGrams":"Float","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event deletetrainingprogram-done **Event topic** : `appaili-aicoach-service-deletetrainingprogram-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `trainingProgram` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`trainingProgram`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"trainingProgram","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"trainingProgram":{"id":"ID","cardioDurationMinutes":"Integer","cardioFrequencyPerWeek":"Integer","cardioType":"String","dailyStepTarget":"Integer","deloadIntervalWeeks":"Integer","notes":"Text","splitType":"String","status":"Enum","status_idx":"Integer","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event moderationrecord-updated **Event topic** : `appaili-aicoach-service-moderationrecord-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecord` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecord`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"moderationRecord":{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event listmymoderationrecords-done **Event topic** : `appaili-aicoach-service-listmymoderationrecords-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `moderationRecords` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`moderationRecords`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"moderationRecords","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","moderationRecords":[{"id":"ID","action":"Enum","action_idx":"Integer","offenseType":"String","reason":"Text","suspensionExpiresAt":"Date","userId":"ID","content":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeals-listed **Event topic** : `appaili-aicoach-service-banappeals-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppealses` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppealses`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppealses","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","banAppealses":[{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","showmoderationRecord":[{"offenseType":"String","reason":"Text","userId":"ID","content":"String"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event banappeal-created **Event topic** : `appaili-aicoach-service-banappeal-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"POST","action":"create","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event banappeal-updated **Event topic** : `appaili-aicoach-service-banappeal-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `banAppeals` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`banAppeals`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"banAppeals","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"banAppeals":{"id":"ID","moderationRecordId":"ID","userId":"ID","appealReason":"String","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquota-created **Event topic** : `appaili-aicoach-service-additionalquota-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"create","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event myadditionalquota-retrived **Event topic** : `appaili-aicoach-service-myadditionalquota-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"GET","action":"get","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"myaddQuota":"Object"} ``` ## Route Event additionalquotapayment-retrived **Event topic** : `appaili-aicoach-service-additionalquotapayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayments-listed **Event topic** : `appaili-aicoach-service-additionalquotapayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_additionalQuotaPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event additionalquotapayment-created **Event topic** : `appaili-aicoach-service-additionalquotapayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-updated **Event topic** : `appaili-aicoach-service-additionalquotapayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-deleted **Event topic** : `appaili-aicoach-service-additionalquotapayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbyorderid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapaymentbypaymentid-retrived **Event topic** : `appaili-aicoach-service-additionalquotapaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_additionalQuotaPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_additionalQuotaPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_additionalQuotaPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_additionalQuotaPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event additionalquotapayment-started **Event topic** : `appaili-aicoach-service-additionalquotapayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-refreshed **Event topic** : `appaili-aicoach-service-additionalquotapayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event additionalquotapayment-calledback **Event topic** : `appaili-aicoach-service-additionalquotapayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `additionalQuota` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`additionalQuota`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"additionalQuota","method":"POST","action":"update","appVersion":"Version","rowCount":1,"additionalQuota":{"id":"ID","userId":"String","additionalMessage":"Integer","status":"Enum","status_idx":"Integer","currency":"String","pricePaid":"Integer","statusUpdatedAt":"Date","activatedAt":"Date","cancelledAt":"Date","periodEnd":"Date","periodStart":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-aicoach-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-aicoach-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-aicoach-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` # Copyright All sources, documents and other digital materials are copyright of . # About Us For more information please visit our website: . . . --- ## Data Objects ### Service Design Specification - Object Design for chatMessage # Service Design Specification - Object Design for chatMessage **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `chatMessage` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for coachConversation # Service Design Specification - Object Design for coachConversation **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `coachConversation` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for mealPlan # Service Design Specification - Object Design for mealPlan **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `mealPlan` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for moderationRecord # Service Design Specification - Object Design for moderationRecord **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `moderationRecord` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for planMeal # Service Design Specification - Object Design for planMeal **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `planMeal` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for programExercise # Service Design Specification - Object Design for programExercise **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `programExercise` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for quotaConfig # Service Design Specification - Object Design for quotaConfig **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `quotaConfig` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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. --- ### Service Design Specification - Object Design for trainingProgram # Service Design Specification - Object Design for trainingProgram **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `trainingProgram` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for userQuota # Service Design Specification - Object Design for userQuota **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `userQuota` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for weightLog # Service Design Specification - Object Design for weightLog **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `weightLog` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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. --- ### Service Design Specification - Object Design for banAppeals # Service Design Specification - Object Design for banAppeals **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `banAppeals` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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. --- ### Service Design Specification - Object Design for additionalQuota # Service Design Specification - Object Design for additionalQuota **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `additionalQuota` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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**: 'additionalquota addition' 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 `'pending'` and will be set to `status`property. `paymentResultCanceled` status will be mapped to a local value using `'cancelled'` and will be set to `status` property. `paymentResultFailed` status will be mapped to a local value using `'failed'` and will be set to `status` property. `paymentResultSuccess` status will be mapped to a local value using `'active'` 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` --- ### Service Design Specification - Object Design for sys_additionalQuotaPayment # Service Design Specification - Object Design for sys_additionalQuotaPayment **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `sys_additionalQuotaPayment` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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'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` --- ### Service Design Specification - Object Design for sys_paymentCustomer # Service Design Specification - Object Design for sys_paymentCustomer **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `sys_paymentCustomer` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for sys_paymentMethod # Service Design Specification - Object Design for sys_paymentMethod **aifitapp-aicoach-service** documentation ## Document Overview This document outlines the object design for the `sys_paymentMethod` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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 APIs ### Business API Design Specification - `Create Chatmessage` # Business API Design Specification - `Create Chatmessage` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createChatMessage` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createChatMessage` Business API is designed to handle a `create` operation on the `ChatMessage` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Send a message to the AI fitness coach. Enforces the full validation chain: subscription check → ban status check → quota check → content flagging → AI processing → tool call execution → quota increment. Returns both the user message and the AI response. ## API Frontend Description By The Backend Architect # Chat Message Creation - This is the primary interaction endpoint for the AI fitness coach. - User sends a message and receives an AI response in the same call. - The response includes the created user message and an aiResponse object containing the AI's reply and any tool calls executed. - If the message is flagged, aiResponse.flagged will be true. - Handle quota exceeded (403) and suspension (403) errors gracefully. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `chatmessage-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createChatMessage` Business API includes a REST controller that can be triggered via the following route: `/v1/chatmessages` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createChatMessage` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createChatMessage` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `chatMessageId` | `ID` | `No` | `-` | `body` | `chatMessageId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `conversationId` | `ID` | `Yes` | `` | `body` | `conversationId` | | **Description:** | The conversation to send the message to | | | | | | | | | | | | | `content` | `Text` | `Yes` | `` | `body` | `content` | | **Description:** | The message content | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createChatMessage` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** ```js { conversationId: runMScript(() => (this.conversationId), {"path":"services[1].businessLogic[0].dataClause.customData[0].value"}), content: runMScript(() => (this.content), {"path":"services[1].businessLogic[0].dataClause.customData[1].value"}), role: runMScript(() => ('user'), {"path":"services[1].businessLogic[0].dataClause.customData[2].value"}), flagged: runMScript(() => (false), {"path":"services[1].businessLogic[0].dataClause.customData[3].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.chatMessageId, content: runMScript(() => (this.content), {"path":"services[1].businessLogic[0].dataClause.customData[1].value"}), conversationId: runMScript(() => (this.conversationId), {"path":"services[1].businessLogic[0].dataClause.customData[0].value"}), flagged: runMScript(() => (false), {"path":"services[1].businessLogic[0].dataClause.customData[3].value"}), role: runMScript(() => ('user'), {"path":"services[1].businessLogic[0].dataClause.customData[2].value"}), toolCallData: this.toolCallData, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : fetchConversationForMsg **Action Type**: `FetchObjectAction` Fetch the conversation to validate ownership ```js class Api { async fetchConversationForMsg() { // Fetch Object on childObject coachConversation const userQuery = { $and: [ { id: runMScript(() => this.conversationId, { path: "services[1].businessLogic[0].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getCoachConversationByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:coachConversation"); } return data ? { id: data["id"], userId: data["userId"], status: data["status"], } : null; } } ``` --- ### [4] Action : checkSubForMsg **Action Type**: `InterserviceCallAction` Check if user has active subscription ```js class Api { async checkSubForMsg() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["userId"] = runMScript(() => this.session.userId, { path: "services[1].businessLogic[0].actions.interserviceCallActions[0].apiParameters[0].value", }); const resp = await InterService.callSubscriptionCheckSubscriptionStatus({ body: bodyParams, }); return resp?.content ?? resp; } } ``` --- ### [5] Action : checkBanForMsg **Action Type**: `FunctionCallAction` Check if user has active ban or suspension ```js class Api { async checkBanForMsg() { try { return await runMScript( () => (async () => await LIB.checkBanStatusFn(this.session.userId))(), { path: "services[1].businessLogic[0].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction checkBanForMsg:", err); throw err; } } } ``` --- ### [6] Action : checkQuotaForMsg **Action Type**: `FunctionCallAction` Check if user has message quota remaining ```js class Api { async checkQuotaForMsg() { try { return await runMScript( () => (async () => await LIB.checkQuotaFn(this.session.userId))(), { path: "services[1].businessLogic[0].actions.functionCallActions[1].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction checkQuotaForMsg:", err); throw err; } } } ``` --- ### [7] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [8] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [9] Action : validateConversationOwnership **Action Type**: `ValidationAction` Ensure user owns the conversation ```js class Api { async validateConversationOwnership() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.fetchedConversation.userId === this.session.userId, { path: "services[1].businessLogic[0].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError("You do not have access to this conversation"); } return isValid; } } ``` --- ### [10] Action : validateConversationActive **Action Type**: `ValidationAction` Ensure the conversation is active ```js class Api { async validateConversationActive() { const isValid = runMScript( () => this.fetchedConversation.status === "active", { path: "services[1].businessLogic[0].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new BadRequestError("This conversation is closed"); } return isValid; } } ``` --- ### [11] Action : validateSubForMsg **Action Type**: `ValidationAction` Active subscription required ```js class Api { async validateSubForMsg() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.activeSubscriptions?.subscriptions && this.activeSubscriptions?.subscriptions.length > 0, { path: "services[1].businessLogic[0].actions.validationActions[2].validationScript", }, ); if (!isValid) { throw new ForbiddenError( "Active subscription required to use the AI coach", ); } return isValid; } } ``` --- ### [12] Action : validateNotBannedForMsg **Action Type**: `ValidationAction` User must not be banned or suspended ```js class Api { async validateNotBannedForMsg() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.banStatus && this.banStatus.isBanned === false, { path: "services[1].businessLogic[0].actions.validationActions[3].validationScript", }, ); if (!isValid) { throw new ForbiddenError("Your account is currently suspended or banned"); } return isValid; } } ``` --- ### [13] Action : validateQuotaForMsg **Action Type**: `ValidationAction` Message quota must not be exceeded ```js class Api { async validateQuotaForMsg() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.quotaCheck && this.quotaCheck.available === true, { path: "services[1].businessLogic[0].actions.validationActions[4].validationScript", }, ); if (!isValid) { throw new ForbiddenError( "Message quota exceeded. Please wait for the next period or contact support.", ); } return isValid; } } ``` --- ### [14] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [15] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [16] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [17] Action : runMessagePipeline **Action Type**: `FunctionCallAction` Main AI processing pipeline: flag content, process with AI coach, execute tool calls, increment quota ```js class Api { async runMessagePipeline() { try { return await runMScript( () => (async () => await LIB.processMessagePipeline(this))(), { path: "services[1].businessLogic[0].actions.functionCallActions[2].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction runMessagePipeline:", err); throw err; } } } ``` --- ### [18] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [19] Action : addAiResponseToOutput **Action Type**: `AddToResponseAction` Add AI response to the API response ```js class Api { async addAiResponseToOutput() { try { this.output["aiResponse"] = runMScript(() => this.aiResponse, { path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[0].contextValue", }); this.output["remainingQuota"] = runMScript( () => this.quotaCheck.remaining, { path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[1].contextValue", }, ); this.output["existQuota"] = runMScript(() => this.quotaCheck.existQuota, { path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[2].contextValue", }); this.output["additionalQuota"] = runMScript( () => this.quotaCheck?.additionalQuota, { path: "services[1].businessLogic[0].actions.addToResponseActions[0].context[3].contextValue", }, ); return true; } catch (error) { console.error("AddToResponseAction error:", error); throw error; } } } ``` --- ### [20] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [21] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createChatMessage` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.body?.["conversationId"] | | content | Text | true | request.body?.["content"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/chatmessages** ```js axios({ method: 'POST', url: '/v1/chatmessages', data: { conversationId:"ID", content:"Text", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`chatMessage`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Create Coachconversation` # Business API Design Specification - `Create Coachconversation` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createCoachConversation` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createCoachConversation` Business API is designed to handle a `create` operation on the `CoachConversation` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Create a new coach conversation. Requires active subscription and no active ban. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `coachconversation-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createCoachConversation` Business API includes a REST controller that can be triggered via the following route: `/v1/coachconversations` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createCoachConversation` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createCoachConversation` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coachConversationId` | `ID` | `No` | `-` | `body` | `coachConversationId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createCoachConversation` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** ```js { status: runMScript(() => ('active'), {"path":"services[1].businessLogic[1].dataClause.customData[0].value"}), userId: runMScript(() => (this.session.userId), {"path":"services[1].businessLogic[1].dataClause.customData[1].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.coachConversationId, status: runMScript(() => ('active'), {"path":"services[1].businessLogic[1].dataClause.customData[0].value"}), userId: runMScript(() => (this.session.userId), {"path":"services[1].businessLogic[1].dataClause.customData[1].value"}), isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : checkSubForConv **Action Type**: `InterserviceCallAction` Check if user has active subscription ```js class Api { async checkSubForConv() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["userId"] = runMScript(() => this.session.userId, { path: "services[1].businessLogic[1].actions.interserviceCallActions[0].apiParameters[0].value", }); const resp = await InterService.callSubscriptionCheckSubscriptionStatus({ body: bodyParams, }); const _respData = resp?.content ?? resp; return _respData?.subscriptions; } } ``` --- ### [4] Action : checkBanForConv **Action Type**: `FunctionCallAction` Check if user has active ban or suspension ```js class Api { async checkBanForConv() { try { return await runMScript( () => (async () => await LIB.checkBanStatusFn(this.session.userId))(), { path: "services[1].businessLogic[1].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction checkBanForConv:", err); throw err; } } } ``` --- ### [5] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [6] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [7] Action : validateSubForConv **Action Type**: `ValidationAction` Subscription must be active ```js class Api { async validateSubForConv() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.activeSubscriptions && this.activeSubscriptions.length > 0, { path: "services[1].businessLogic[1].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError( "Active subscription required to use the AI coach", ); } return isValid; } } ``` --- ### [8] Action : validateNotBannedForConv **Action Type**: `ValidationAction` User must not be banned or suspended ```js class Api { async validateNotBannedForConv() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.banStatus && this.banStatus.isBanned === false, { path: "services[1].businessLogic[1].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new ForbiddenError("Your account is currently suspended or banned"); } return isValid; } } ``` --- ### [9] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [10] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [11] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [12] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [13] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [14] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createCoachConversation` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/coachconversations** ```js axios({ method: 'POST', url: '/v1/coachconversations', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`coachConversation`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coachConversation": { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "activeSubscriptions": "Object" } ``` --- ### Business API Design Specification - `Create Quotaconfig` # Business API Design Specification - `Create Quotaconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createQuotaConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createQuotaConfig` Business API is designed to handle a `create` operation on the `QuotaConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Create a quota configuration record. Admin only. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `quotaconfig-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createQuotaConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/quotaconfigs` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createQuotaConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createQuotaConfig` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `quotaConfigId` | `ID` | `No` | `-` | `body` | `quotaConfigId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `quotaLimit` | `Integer` | `Yes` | `-` | `body` | `quotaLimit` | | **Description:** | Maximum messages allowed per period | | | | | | | | | | | | | `quotaPeriod` | `Enum` | `Yes` | `-` | `body` | `quotaPeriod` | | **Description:** | Period over which the quota is measured | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createQuotaConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin`, `superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.quotaConfigId, quotaLimit: this.quotaLimit, quotaPeriod: this.quotaPeriod, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createQuotaConfig` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaLimit | Integer | true | request.body?.["quotaLimit"] | | quotaPeriod | Enum | true | request.body?.["quotaPeriod"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/quotaconfigs** ```js axios({ method: 'POST', url: '/v1/quotaconfigs', data: { quotaLimit:"Integer", quotaPeriod:"Enum", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`quotaConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Create Weightlog` # Business API Design Specification - `Create Weightlog` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createWeightLog` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createWeightLog` Business API is designed to handle a `create` operation on the `WeightLog` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Report a weight measurement. Requires active subscription and no active ban. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `weightlog-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createWeightLog` Business API includes a REST controller that can be triggered via the following route: `/v1/weightlogs` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createWeightLog` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createWeightLog` Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `weightLogId` | `ID` | `No` | `-` | `body` | `weightLogId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `measuredAt` | `Date` | `Yes` | `-` | `body` | `measuredAt` | | **Description:** | Date and time of measurement | | | | | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `session` | `userId` | | **Description:** | Reference to the user who recorded this weight | | | | | | | | | | | | | `weightKg` | `Float` | `Yes` | `-` | `body` | `weightKg` | | **Description:** | Body weight in kilograms | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createWeightLog` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.weightLogId, measuredAt: this.measuredAt, userId: this.userId, weightKg: this.weightKg, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : checkSubForWeight **Action Type**: `InterserviceCallAction` Check subscription status ```js class Api { async checkSubForWeight() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["userId"] = runMScript(() => this.session.userId, { path: "services[1].businessLogic[3].actions.interserviceCallActions[0].apiParameters[0].value", }); const resp = await InterService.callSubscriptionCheckSubscriptionStatus({ body: bodyParams, }); return resp?.content ?? resp; } } ``` --- ### [4] Action : checkBanForWeight **Action Type**: `FunctionCallAction` Check ban status ```js class Api { async checkBanForWeight() { try { return await runMScript( () => (async () => await LIB.checkBanStatusFn(this.session.userId))(), { path: "services[1].businessLogic[3].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction checkBanForWeight:", err); throw err; } } } ``` --- ### [5] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [6] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [7] Action : validateSubForWeight **Action Type**: `ValidationAction` Active subscription required ```js class Api { async validateSubForWeight() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.activeSubscriptions?.subscriptions && this.activeSubscriptions?.subscriptions.length > 0, { path: "services[1].businessLogic[3].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError("Active subscription required"); } return isValid; } } ``` --- ### [8] Action : validateNotBannedForWeight **Action Type**: `ValidationAction` User must not be banned ```js class Api { async validateNotBannedForWeight() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.banStatus && this.banStatus.isBanned === false, { path: "services[1].businessLogic[3].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new ForbiddenError("Your account is currently suspended or banned"); } return isValid; } } ``` --- ### [9] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [10] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [11] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [12] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [13] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [14] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createWeightLog` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | measuredAt | Date | true | request.body?.["measuredAt"] | | weightKg | Float | true | request.body?.["weightKg"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/weightlogs** ```js axios({ method: 'POST', url: '/v1/weightlogs', data: { measuredAt:"Date", weightKg:"Float", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`weightLog`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLog", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "weightLog": { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Chatmessage` # Business API Design Specification - `Get Chatmessage` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getChatMessage` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getChatMessage` Business API is designed to handle a `get` operation on the `ChatMessage` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a chat message by ID with parent conversation ownership validation. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getChatMessage` Business API includes a REST controller that can be triggered via the following route: `/v1/chatmessages/:chatMessageId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getChatMessage` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getChatMessage` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `chatMessageId` | `ID` | `Yes` | `-` | `urlpath` | `chatMessageId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getChatMessage` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.chatMessageId},{isActive:true}]}), {"path":"services[1].businessLogic[4].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Action : fetchConvForGetMsg **Action Type**: `FetchObjectAction` Fetch conversation to validate ownership ```js class Api { async fetchConvForGetMsg() { // Fetch Object on childObject coachConversation const userQuery = { $and: [ { id: runMScript(() => this.chatMessage.conversationId, { path: "services[1].businessLogic[4].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getCoachConversationByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:coachConversation"); } return data ? { id: data["id"], userId: data["userId"], } : null; } } ``` --- ### [9] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [10] Action : validateMsgOwnership **Action Type**: `ValidationAction` Ensure user owns the parent conversation ```js class Api { async validateMsgOwnership() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.parentConversation.userId === this.session.userId || ["admin", "superAdmin"].includes(this.session.roleId), { path: "services[1].businessLogic[4].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError("You do not have access to this message"); } return isValid; } } ``` --- ### [11] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [12] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [13] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getChatMessage` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/chatmessages/:chatMessageId** ```js axios({ method: 'GET', url: `/v1/chatmessages/${chatMessageId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`chatMessage`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Coachconversation` # Business API Design Specification - `Get Coachconversation` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getCoachConversation` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getCoachConversation` Business API is designed to handle a `get` operation on the `CoachConversation` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a conversation by ID. Users see their own, admins can see any. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getCoachConversation` Business API includes a REST controller that can be triggered via the following route: `/v1/coachconversations/:coachConversationId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getCoachConversation` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getCoachConversation` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coachConversationId` | `ID` | `Yes` | `-` | `urlpath` | `coachConversationId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getCoachConversation` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.coachConversationId},{isActive:true}]}), {"path":"services[1].businessLogic[5].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getCoachConversation` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coachConversationId | ID | true | request.params?.["coachConversationId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coachconversations/:coachConversationId** ```js axios({ method: 'GET', url: `/v1/coachconversations/${coachConversationId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`coachConversation`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coachConversation": { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Mealplan` # Business API Design Specification - `Get Mealplan` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getMealPlan` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getMealPlan` Business API is designed to handle a `get` operation on the `MealPlan` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a meal plan by ID with meals. Users see their own, admins can see any. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getMealPlan` Business API includes a REST controller that can be triggered via the following route: `/v1/mealplans/:mealPlanId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getMealPlan` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getMealPlan` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `mealPlanId` | `ID` | `Yes` | `-` | `urlpath` | `mealPlanId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getMealPlan` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.mealPlanId},{isActive:true}]}), {"path":"services[1].businessLogic[6].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getMealPlan` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.params?.["mealPlanId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/mealplans/:mealPlanId** ```js axios({ method: 'GET', url: `/v1/mealplans/${mealPlanId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`mealPlan`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlan", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "mealPlan": { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "meals": [ { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ] } } ``` --- ### Business API Design Specification - `Get Moderationrecord` # Business API Design Specification - `Get Moderationrecord` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getModerationRecord` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getModerationRecord` Business API is designed to handle a `get` operation on the `ModerationRecord` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a moderation record by ID. Admin only. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getModerationRecord` Business API includes a REST controller that can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getModerationRecord` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getModerationRecord` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `moderationRecordId` | `ID` | `Yes` | `-` | `urlpath` | `moderationRecordId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getModerationRecord` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin`, `superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.moderationRecordId}), {"path":"services[1].businessLogic[7].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getModerationRecord` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'GET', url: `/v1/moderationrecords/${moderationRecordId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`moderationRecord`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `Get Myquota` # Business API Design Specification - `Get Myquota` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getMyQuota` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getMyQuota` Business API is designed to handle a `get` operation on the `UserQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get the current user's quota usage for the active period. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getMyQuota` Business API includes a REST controller that can be triggered via the following route: `/v1/my-quota` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getMyQuota` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getMyQuota` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getMyQuota` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {userId: this.session.userId} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId: this.session.userId},{isActive:true}]}), {"path":"services[1].businessLogic[8].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Action : checkquota **Action Type**: `FunctionCallAction` ```js class Api { async checkquota() { try { return await runMScript( () => (async () => await LIB.checkQuotaFn(this.session.userId))(), { path: "services[1].businessLogic[8].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction checkquota:", err); throw err; } } } ``` --- ### [11] Action : addremainingquota **Action Type**: `AddToResponseAction` ```js class Api { async addremainingquota() { try { this.output["quotaResponse"] = runMScript(() => this.quotaResponse, { path: "services[1].businessLogic[8].actions.addToResponseActions[0].context[0].contextValue", }); return true; } catch (error) { console.error("AddToResponseAction error:", error); throw error; } } } ``` --- ### [12] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [13] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getMyQuota` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/my-quota** ```js axios({ method: 'GET', url: '/v1/my-quota', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`userQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userQuota": { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Planmeal` # Business API Design Specification - `Get Planmeal` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getPlanMeal` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getPlanMeal` Business API is designed to handle a `get` operation on the `PlanMeal` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a plan meal by ID with parent ownership validation. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getPlanMeal` Business API includes a REST controller that can be triggered via the following route: `/v1/planmeals/:planMealId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getPlanMeal` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getPlanMeal` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `planMealId` | `ID` | `Yes` | `-` | `urlpath` | `planMealId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getPlanMeal` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.planMealId},{isActive:true}]}), {"path":"services[1].businessLogic[9].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Action : fetchParentMealPlan **Action Type**: `FetchObjectAction` Fetch the parent meal plan to validate ownership ```js class Api { async fetchParentMealPlan() { // Fetch Object on childObject mealPlan const userQuery = { $and: [ { id: runMScript(() => this.planMeal.mealPlanId, { path: "services[1].businessLogic[9].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getMealPlanByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:mealPlan"); } return data; } } ``` --- ### [9] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [10] Action : validateMealOwnership **Action Type**: `ValidationAction` Ensure user owns the parent meal plan ```js class Api { async validateMealOwnership() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.parentMealPlan.userId === this.session.userId || ["admin", "superAdmin"].includes(this.session.roleId), { path: "services[1].businessLogic[9].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError("You do not have access to this meal"); } return isValid; } } ``` --- ### [11] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [12] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [13] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getPlanMeal` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | planMealId | ID | true | request.params?.["planMealId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/planmeals/:planMealId** ```js axios({ method: 'GET', url: `/v1/planmeals/${planMealId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`planMeal`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "planMeal", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "planMeal": { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Programexercise` # Business API Design Specification - `Get Programexercise` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getProgramExercise` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getProgramExercise` Business API is designed to handle a `get` operation on the `ProgramExercise` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a program exercise by ID with parent ownership validation. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getProgramExercise` Business API includes a REST controller that can be triggered via the following route: `/v1/programexercises/:programExerciseId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getProgramExercise` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getProgramExercise` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `programExerciseId` | `ID` | `Yes` | `-` | `urlpath` | `programExerciseId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getProgramExercise` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.programExerciseId},{isActive:true}]}), {"path":"services[1].businessLogic[10].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Action : fetchParentProgram **Action Type**: `FetchObjectAction` Fetch the parent training program to validate ownership ```js class Api { async fetchParentProgram() { // Fetch Object on childObject trainingProgram const userQuery = { $and: [ { id: runMScript(() => this.programExercise.trainingProgramId, { path: "services[1].businessLogic[10].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getTrainingProgramByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:trainingProgram"); } return data; } } ``` --- ### [9] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [10] Action : validateExerciseOwnership **Action Type**: `ValidationAction` Ensure the user owns the parent training program ```js class Api { async validateExerciseOwnership() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.parentProgram.userId === this.session.userId || ["admin", "superAdmin"].includes(this.session.roleId), { path: "services[1].businessLogic[10].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError("You do not have access to this exercise"); } return isValid; } } ``` --- ### [11] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [12] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [13] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getProgramExercise` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | programExerciseId | ID | true | request.params?.["programExerciseId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/programexercises/:programExerciseId** ```js axios({ method: 'GET', url: `/v1/programexercises/${programExerciseId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`programExercise`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "programExercise", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "programExercise": { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Quotaconfig` # Business API Design Specification - `Get Quotaconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getQuotaConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getQuotaConfig` Business API is designed to handle a `get` operation on the `QuotaConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a quota configuration record. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getQuotaConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/quotaconfigs/:quotaConfigId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getQuotaConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getQuotaConfig` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `quotaConfigId` | `ID` | `Yes` | `-` | `urlpath` | `quotaConfigId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getQuotaConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.quotaConfigId},{isActive:true}]}), {"path":"services[1].businessLogic[11].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getQuotaConfig` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaConfigId | ID | true | request.params?.["quotaConfigId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/quotaconfigs/:quotaConfigId** ```js axios({ method: 'GET', url: `/v1/quotaconfigs/${quotaConfigId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`quotaConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Trainingprogram` # Business API Design Specification - `Get Trainingprogram` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getTrainingProgram` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getTrainingProgram` Business API is designed to handle a `get` operation on the `TrainingProgram` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a training program by ID. Users see their own programs, admins can see any. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getTrainingProgram` Business API includes a REST controller that can be triggered via the following route: `/v1/trainingprograms/:trainingProgramId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getTrainingProgram` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getTrainingProgram` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `trainingProgramId` | `ID` | `Yes` | `-` | `urlpath` | `trainingProgramId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getTrainingProgram` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.trainingProgramId},{isActive:true}]}), {"path":"services[1].businessLogic[12].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getTrainingProgram` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.params?.["trainingProgramId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/trainingprograms/:trainingProgramId** ```js axios({ method: 'GET', url: `/v1/trainingprograms/${trainingProgramId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`trainingProgram`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingProgram", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "trainingProgram": { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "exercises": [ { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ] } } ``` --- ### Business API Design Specification - `Get Userquota` # Business API Design Specification - `Get Userquota` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getUserQuota` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getUserQuota` Business API is designed to handle a `get` operation on the `UserQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a user quota record. Users see their own, admins can see any. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getUserQuota` Business API includes a REST controller that can be triggered via the following route: `/v1/userquotas/:userQuotaId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getUserQuota` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getUserQuota` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userQuotaId` | `ID` | `Yes` | `-` | `urlpath` | `userQuotaId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getUserQuota` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.userQuotaId},{isActive:true}]}), {"path":"services[1].businessLogic[13].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Action : fetchAdditionalQuota **Action Type**: `FunctionCallAction` fetchAdditionalQuota ```js class Api { async fetchAdditionalQuota() { try { return await runMScript( () => (async () => await LIB.fetchAdditionalQuota(this.session.userId))(), { path: "services[1].businessLogic[13].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction fetchAdditionalQuota:", err); throw err; } } } ``` --- ### [11] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [12] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getUserQuota` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userQuotaId | ID | true | request.params?.["userQuotaId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/userquotas/:userQuotaId** ```js axios({ method: 'GET', url: `/v1/userquotas/${userQuotaId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`userQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userQuota": { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "additionalQuota": "Object" } ``` --- ### Business API Design Specification - `Get Weightlog` # Business API Design Specification - `Get Weightlog` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getWeightLog` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getWeightLog` Business API is designed to handle a `get` operation on the `WeightLog` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get a weight log entry by ID. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getWeightLog` Business API includes a REST controller that can be triggered via the following route: `/v1/weightlogs/:weightLogId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getWeightLog` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getWeightLog` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `weightLogId` | `ID` | `Yes` | `-` | `urlpath` | `weightLogId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getWeightLog` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.weightLogId},{isActive:true}]}), {"path":"services[1].businessLogic[14].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getWeightLog` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | weightLogId | ID | true | request.params?.["weightLogId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/weightlogs/:weightLogId** ```js axios({ method: 'GET', url: `/v1/weightlogs/${weightLogId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`weightLog`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "weightLog": { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Chatmessages` # Business API Design Specification - `List Chatmessages` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listChatMessages` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listChatMessages` Business API is designed to handle a `list` operation on the `ChatMessage` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List chat messages for a conversation with parent ownership validation. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listChatMessages` Business API includes a REST controller that can be triggered via the following route: `/v1/chatmessages` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listChatMessages` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listChatMessages` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `conversationId` | `ID` | `Yes` | `` | `query` | `conversationId` | | **Description:** | The conversation to list messages for | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listChatMessages` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {conversationId: this.conversationId} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{conversationId: this.conversationId},{isActive:true}]}), {"path":"services[1].businessLogic[15].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : fetchConvForListMsg **Action Type**: `FetchObjectAction` Fetch conversation to validate ownership ```js class Api { async fetchConvForListMsg() { // Fetch Object on childObject coachConversation const userQuery = { $and: [ { id: runMScript(() => this.conversationId, { path: "services[1].businessLogic[15].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getCoachConversationByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:coachConversation"); } return data ? { id: data["id"], userId: data["userId"], } : null; } } ``` --- ### [4] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [5] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [6] Action : validateConvOwnershipForListMsg **Action Type**: `ValidationAction` Ensure user owns the conversation ```js class Api { async validateConvOwnershipForListMsg() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.parentConversation.userId === this.session.userId || ["admin", "superAdmin"].includes(this.session.roleId), { path: "services[1].businessLogic[15].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError( "You do not have access to this conversation's messages", ); } return isValid; } } ``` --- ### [7] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [8] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [9] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [10] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [11] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [12] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listChatMessages` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.query?.["conversationId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/chatmessages** ```js axios({ method: 'GET', url: '/v1/chatmessages', data: { }, params: { conversationId:'"ID"', } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`chatMessages`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "chatMessages": [ { "id": "ID", "content": "Text", "conversationId": "ID", "flagged": "Boolean", "role": "Enum", "role_idx": "Integer", "toolCallData": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Coachconversations` # Business API Design Specification - `List Coachconversations` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listCoachConversations` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listCoachConversations` Business API is designed to handle a `list` operation on the `CoachConversation` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List conversations. Users see their own, admins can see all. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listCoachConversations` Business API includes a REST controller that can be triggered via the following route: `/v1/coachconversations` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listCoachConversations` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listCoachConversations` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listCoachConversations` api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `status` Filter **Type:** `Enum` **Description:** Conversation status **Location:** Query Parameter **Usage:** - Single value: `?status=` (case-insensitive) - Multiple values: `?status=&status=` - Null check: `?status=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/coachconversations?status=active // Get records with multiple enum values (use multiple parameters) GET /v1/coachconversations?status=active&status=pending // Get records without this field GET /v1/coachconversations?status=null ``` #### `userId` Filter **Type:** `ID` **Description:** Reference to the user who owns this conversation **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/coachconversations?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/coachconversations?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/coachconversations?userId=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listCoachConversations` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true,userId:this.session?.userId}), {"path":"services[1].businessLogic[16].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listCoachConversations` api has 2 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | status | Enum | No | Conversation status | | userId | ID | No | Reference to the user who owns this conversation | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coachconversations** ```js axios({ method: 'GET', url: '/v1/coachconversations', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`coachConversations`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coachConversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coachConversations": [ { "id": "ID", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Mealplans` # Business API Design Specification - `List Mealplans` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listMealPlans` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listMealPlans` Business API is designed to handle a `list` operation on the `MealPlan` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List meal plans. Users see their own, admins can see all. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listMealPlans` Business API includes a REST controller that can be triggered via the following route: `/v1/mealplans` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listMealPlans` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listMealPlans` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listMealPlans` api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `status` Filter **Type:** `Enum` **Description:** Meal plan status **Location:** Query Parameter **Usage:** - Single value: `?status=` (case-insensitive) - Multiple values: `?status=&status=` - Null check: `?status=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/mealplans?status=active // Get records with multiple enum values (use multiple parameters) GET /v1/mealplans?status=active&status=pending // Get records without this field GET /v1/mealplans?status=null ``` #### `userId` Filter **Type:** `ID` **Description:** Reference to the user who owns this meal plan **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/mealplans?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/mealplans?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/mealplans?userId=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listMealPlans` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true,userId:this.session?.userId}), {"path":"services[1].businessLogic[17].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listMealPlans` api has 2 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | status | Enum | No | Meal plan status | | userId | ID | No | Reference to the user who owns this meal plan | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/mealplans** ```js axios({ method: 'GET', url: '/v1/mealplans', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`mealPlans`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlans", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "mealPlans": [ { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Moderationrecords` # Business API Design Specification - `List Moderationrecords` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listModerationRecords` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listModerationRecords` Business API is designed to handle a `list` operation on the `ModerationRecord` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List moderation records. Admin only. Supports filtering by userId and action. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listModerationRecords` Business API includes a REST controller that can be triggered via the following route: `/v1/moderationrecords` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listModerationRecords` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listModerationRecords` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listModerationRecords` api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `action` Filter **Type:** `Enum` **Description:** Moderation action taken **Location:** Query Parameter **Usage:** - Single value: `?action=` (case-insensitive) - Multiple values: `?action=&action=` - Null check: `?action=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/moderationrecords?action=active // Get records with multiple enum values (use multiple parameters) GET /v1/moderationrecords?action=active&action=pending // Get records without this field GET /v1/moderationrecords?action=null ``` #### `userId` Filter **Type:** `ID` **Description:** Reference to the user who was moderated **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/moderationrecords?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/moderationrecords?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/moderationrecords?userId=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listModerationRecords` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin`, `superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js null ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listModerationRecords` api has 2 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | action | Enum | No | Moderation action taken | | userId | ID | No | Reference to the user who was moderated | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/moderationrecords** ```js axios({ method: 'GET', url: '/v1/moderationrecords', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // action: '' // Filter by action // userId: '' // Filter by userId } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`moderationRecords`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "moderationRecords": [ { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Planmeals` # Business API Design Specification - `List Planmeals` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listPlanMeals` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listPlanMeals` Business API is designed to handle a `list` operation on the `PlanMeal` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List meals for a meal plan with parent ownership validation. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listPlanMeals` Business API includes a REST controller that can be triggered via the following route: `/v1/planmeals` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listPlanMeals` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPlanMeals` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `mealPlanId` | `ID` | `Yes` | `` | `query` | `mealPlanId` | | **Description:** | The meal plan ID to list meals for | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listPlanMeals` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {mealPlanId: this.mealPlanId} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{mealPlanId: this.mealPlanId},{isActive:true}]}), {"path":"services[1].businessLogic[19].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ sortOrder asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : fetchParentMealPlanForList **Action Type**: `FetchObjectAction` Fetch the parent meal plan to validate ownership ```js class Api { async fetchParentMealPlanForList() { // Fetch Object on childObject mealPlan const userQuery = { $and: [ { id: runMScript(() => this.mealPlanId, { path: "services[1].businessLogic[19].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getMealPlanByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:mealPlan"); } return data ? { id: data["id"], userId: data["userId"], } : null; } } ``` --- ### [4] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [5] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [6] Action : validateMealPlanOwnershipForList **Action Type**: `ValidationAction` Ensure user owns the parent meal plan ```js class Api { async validateMealPlanOwnershipForList() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.parentMealPlan.userId === this.session.userId || ["admin", "superAdmin"].includes(this.session.roleId), { path: "services[1].businessLogic[19].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError( "You do not have access to this meal plan's meals", ); } return isValid; } } ``` --- ### [7] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [8] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [9] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [10] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [11] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [12] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listPlanMeals` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.query?.["mealPlanId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/planmeals** ```js axios({ method: 'GET', url: '/v1/planmeals', data: { }, params: { mealPlanId:'"ID"', } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`planMeals`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "planMeals", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "planMeals": [ { "id": "ID", "carbs": "Float", "fat": "Float", "foods": "Text", "mealLabel": "String", "mealPlanId": "ID", "protein": "Float", "sortOrder": "Integer", "totalCalories": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Programexercises` # Business API Design Specification - `List Programexercises` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listProgramExercises` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listProgramExercises` Business API is designed to handle a `list` operation on the `ProgramExercise` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List exercises for a training program. Validates parent program ownership. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listProgramExercises` Business API includes a REST controller that can be triggered via the following route: `/v1/programexercises` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listProgramExercises` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listProgramExercises` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `trainingProgramId` | `ID` | `Yes` | `` | `query` | `trainingProgramId` | | **Description:** | The training program ID to list exercises for | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listProgramExercises` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {trainingProgramId: this.trainingProgramId} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{trainingProgramId: this.trainingProgramId},{isActive:true}]}), {"path":"services[1].businessLogic[20].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ sortOrder asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : fetchParentProgramForList **Action Type**: `FetchObjectAction` Fetch the parent training program to validate ownership ```js class Api { async fetchParentProgramForList() { // Fetch Object on childObject trainingProgram const userQuery = { $and: [ { id: runMScript(() => this.trainingProgramId, { path: "services[1].businessLogic[20].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getTrainingProgramByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:trainingProgram"); } return data ? { id: data["id"], userId: data["userId"], } : null; } } ``` --- ### [4] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [5] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [6] Action : validateProgramOwnershipForList **Action Type**: `ValidationAction` Ensure user owns the parent training program ```js class Api { async validateProgramOwnershipForList() { if (this.checkAbsolute()) return true; const isValid = runMScript( () => this.parentProgram.userId === this.session.userId || ["admin", "superAdmin"].includes(this.session.roleId), { path: "services[1].businessLogic[20].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new ForbiddenError( "You do not have access to this program's exercises", ); } return isValid; } } ``` --- ### [7] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [8] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [9] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [10] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [11] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [12] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listProgramExercises` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.query?.["trainingProgramId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/programexercises** ```js axios({ method: 'GET', url: '/v1/programexercises', data: { }, params: { trainingProgramId:'"ID"', } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`programExercises`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "programExercises", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "programExercises": [ { "id": "ID", "dayLabel": "String", "exerciseName": "String", "movementType": "Enum", "movementType_idx": "Integer", "muscleGroup": "String", "progressionRule": "Text", "repMax": "Integer", "repMin": "Integer", "rirTarget": "Integer", "sets": "Integer", "sortOrder": "Integer", "trainingProgramId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Quotaconfigs` # Business API Design Specification - `List Quotaconfigs` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listQuotaConfigs` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listQuotaConfigs` Business API is designed to handle a `list` operation on the `QuotaConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List quota configuration records. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listQuotaConfigs` Business API includes a REST controller that can be triggered via the following route: `/v1/quotaconfigs` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listQuotaConfigs` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listQuotaConfigs` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listQuotaConfigs` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[21].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listQuotaConfigs` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/quotaconfigs** ```js axios({ method: 'GET', url: '/v1/quotaconfigs', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`quotaConfigs`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "quotaConfigs": [ { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Trainingprograms` # Business API Design Specification - `List Trainingprograms` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listTrainingPrograms` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listTrainingPrograms` Business API is designed to handle a `list` operation on the `TrainingProgram` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List training programs. Users see their own programs, admins can see all. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listTrainingPrograms` Business API includes a REST controller that can be triggered via the following route: `/v1/trainingprograms` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listTrainingPrograms` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listTrainingPrograms` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listTrainingPrograms` api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `status` Filter **Type:** `Enum` **Description:** Program status **Location:** Query Parameter **Usage:** - Single value: `?status=` (case-insensitive) - Multiple values: `?status=&status=` - Null check: `?status=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/trainingprograms?status=active // Get records with multiple enum values (use multiple parameters) GET /v1/trainingprograms?status=active&status=pending // Get records without this field GET /v1/trainingprograms?status=null ``` #### `userId` Filter **Type:** `ID` **Description:** Reference to the user who owns this training program **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/trainingprograms?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/trainingprograms?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/trainingprograms?userId=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listTrainingPrograms` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true,userId:this.session?.userId}), {"path":"services[1].businessLogic[22].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listTrainingPrograms` api has 2 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | status | Enum | No | Program status | | userId | ID | No | Reference to the user who owns this training program | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/trainingprograms** ```js axios({ method: 'GET', url: '/v1/trainingprograms', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // status: '' // Filter by status // userId: '' // Filter by userId } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`trainingPrograms`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingPrograms", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "trainingPrograms": [ { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Userquotas` # Business API Design Specification - `List Userquotas` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listUserQuotas` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listUserQuotas` Business API is designed to handle a `list` operation on the `UserQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List all user quotas. Admin only. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listUserQuotas` Business API includes a REST controller that can be triggered via the following route: `/v1/userquotas` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listUserQuotas` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listUserQuotas` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listUserQuotas` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `userId` Filter **Type:** `ID` **Description:** Reference to the user whose quota is being tracked **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/userquotas?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/userquotas?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/userquotas?userId=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listUserQuotas` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin`, `superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[23].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ messageCount desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listUserQuotas` api has 1 filter parameter available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | userId | ID | No | Reference to the user whose quota is being tracked | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/userquotas** ```js axios({ method: 'GET', url: '/v1/userquotas', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // userId: '' // Filter by userId } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`userQuotas`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userQuotas", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userQuotas": [ { "id": "ID", "messageCount": "Integer", "periodEnd": "Date", "periodStart": "Date", "userId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Weightlogs` # Business API Design Specification - `List Weightlogs` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listWeightLogs` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listWeightLogs` Business API is designed to handle a `list` operation on the `WeightLog` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List weight log entries. Users see their own, admins see all. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listWeightLogs` Business API includes a REST controller that can be triggered via the following route: `/v1/weightlogs` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listWeightLogs` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listWeightLogs` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listWeightLogs` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true,userId:this.session?.userId}), {"path":"services[1].businessLogic[24].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ measuredAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listWeightLogs` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/weightlogs** ```js axios({ method: 'GET', url: '/v1/weightlogs', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`weightLogs`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "weightLogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "weightLogs": [ { "id": "ID", "measuredAt": "Date", "userId": "ID", "weightKg": "Float", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Update Quotaconfig` # Business API Design Specification - `Update Quotaconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateQuotaConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateQuotaConfig` Business API is designed to handle a `update` operation on the `QuotaConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Update a quota configuration record. Admin only. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `quotaconfig-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateQuotaConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/quotaconfigs/:quotaConfigId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateQuotaConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateQuotaConfig` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `quotaConfigId` | `ID` | `Yes` | `-` | `urlpath` | `quotaConfigId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `quotaLimit` | `Integer` | `No` | `-` | `body` | `quotaLimit` | | **Description:** | Maximum messages allowed per period | | | | | | | | | | | | | `quotaPeriod` | `Enum` | `No` | `-` | `body` | `quotaPeriod` | | **Description:** | Period over which the quota is measured | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateQuotaConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin`, `superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.quotaConfigId},{isActive:true}]}), {"path":"services[1].businessLogic[25].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { quotaLimit: this.quotaLimit, quotaPeriod: this.quotaPeriod, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateQuotaConfig` api has got 3 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | quotaConfigId | ID | true | request.params?.["quotaConfigId"] | | quotaLimit | Integer | false | request.body?.["quotaLimit"] | | quotaPeriod | Enum | false | request.body?.["quotaPeriod"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/quotaconfigs/:quotaConfigId** ```js axios({ method: 'PATCH', url: `/v1/quotaconfigs/${quotaConfigId}`, data: { quotaLimit:"Integer", quotaPeriod:"Enum", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`quotaConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "quotaConfig", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "quotaConfig": { "id": "ID", "quotaLimit": "Integer", "quotaPeriod": "Enum", "quotaPeriod_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Moderationrecord` # Business API Design Specification - `Delete Moderationrecord` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deleteModerationRecord` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deleteModerationRecord` Business API is designed to handle a `delete` operation on the `ModerationRecord` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `moderationrecord-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deleteModerationRecord` Business API includes a REST controller that can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deleteModerationRecord` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteModerationRecord` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `moderationRecordId` | `ID` | `Yes` | `-` | `urlpath` | `moderationRecordId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deleteModerationRecord` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.moderationRecordId}), {"path":"services[1].businessLogic[26].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deleteModerationRecord` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'DELETE', url: `/v1/moderationrecords/${moderationRecordId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`moderationRecord`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` --- ### Business API Design Specification - `Do Deletemealplan` # Business API Design Specification - `Do Deletemealplan` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deletemealplan` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deletemealplan` Business API is designed to handle a `delete` operation on the `MealPlan` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `deletemealplan-done` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deletemealplan` Business API includes a REST controller that can be triggered via the following route: `/v1/deletemealplan/:mealPlanId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deletemealplan` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deletemealplan` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `mealPlanId` | `ID` | `Yes` | `-` | `urlpath` | `mealPlanId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deletemealplan` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.mealPlanId},{isActive:true}]}), {"path":"services[1].businessLogic[27].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deletemealplan` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | mealPlanId | ID | true | request.params?.["mealPlanId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/deletemealplan/:mealPlanId** ```js axios({ method: 'DELETE', url: `/v1/deletemealplan/${mealPlanId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`mealPlan`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "mealPlan", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "mealPlan": { "id": "ID", "carbGrams": "Float", "dailyCalorieTarget": "Integer", "fatGrams": "Float", "notes": "Text", "proteinGrams": "Float", "restDayCalories": "Integer", "restDayCarbGrams": "Float", "status": "Enum", "status_idx": "Integer", "trainingDayCalories": "Integer", "trainingDayCarbGrams": "Float", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Do Deletetrainingprogram` # Business API Design Specification - `Do Deletetrainingprogram` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deletetrainingprogram` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deletetrainingprogram` Business API is designed to handle a `delete` operation on the `TrainingProgram` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `deletetrainingprogram-done` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deletetrainingprogram` Business API includes a REST controller that can be triggered via the following route: `/v1/deletetrainingprogram/:trainingProgramId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deletetrainingprogram` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deletetrainingprogram` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `trainingProgramId` | `ID` | `Yes` | `-` | `urlpath` | `trainingProgramId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deletetrainingprogram` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.trainingProgramId},{isActive:true}]}), {"path":"services[1].businessLogic[28].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deletetrainingprogram` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | trainingProgramId | ID | true | request.params?.["trainingProgramId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/deletetrainingprogram/:trainingProgramId** ```js axios({ method: 'DELETE', url: `/v1/deletetrainingprogram/${trainingProgramId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`trainingProgram`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "trainingProgram", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "trainingProgram": { "id": "ID", "cardioDurationMinutes": "Integer", "cardioFrequencyPerWeek": "Integer", "cardioType": "String", "dailyStepTarget": "Integer", "deloadIntervalWeeks": "Integer", "notes": "Text", "splitType": "String", "status": "Enum", "status_idx": "Integer", "userId": "ID", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Moderationrecord` # Business API Design Specification - `Update Moderationrecord` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateModerationRecord` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateModerationRecord` Business API is designed to handle a `update` operation on the `ModerationRecord` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `moderationrecord-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateModerationRecord` Business API includes a REST controller that can be triggered via the following route: `/v1/moderationrecords/:moderationRecordId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateModerationRecord` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateModerationRecord` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `moderationRecordId` | `ID` | `Yes` | `-` | `urlpath` | `moderationRecordId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `action` | `String` | `Yes` | `` | `body` | `action` | | **Description:** | - | | | | | | | | | | | | | `content` | `String` | `No` | `-` | `body` | `content` | | **Description:** | | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateModerationRecord` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.moderationRecordId}), {"path":"services[1].businessLogic[29].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { action: runMScript(() => (this.action), {"path":"services[1].businessLogic[29].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { content: this.content, // action parameter is closed to update by client request // include it in data clause unless you are sure action: runMScript(() => (this.action), {"path":"services[1].businessLogic[29].dataClause.customData[0].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateModerationRecord` api has got 3 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.params?.["moderationRecordId"] | | action | String | true | request.body?.["action"] | | content | String | false | request.body?.["content"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/moderationrecords/:moderationRecordId** ```js axios({ method: 'PATCH', url: `/v1/moderationrecords/${moderationRecordId}`, data: { action:"String", content:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`moderationRecord`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecord", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "moderationRecord": { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `Do Listmymoderationrecords` # Business API Design Specification - `Do Listmymoderationrecords` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listmymoderationrecords` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listmymoderationrecords` Business API is designed to handle a `list` operation on the `ModerationRecord` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `listmymoderationrecords-done` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listmymoderationrecords` Business API includes a REST controller that can be triggered via the following route: `/v1/listmymoderationrecords` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listmymoderationrecords` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listmymoderationrecords` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `No` | `` | `session` | `userId` | | **Description:** | - | | | | | | | | | | | | ### Filter Parameters The `listmymoderationrecords` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `action` Filter **Type:** `Enum` **Description:** Moderation action taken **Location:** Query Parameter **Usage:** - Single value: `?action=` (case-insensitive) - Multiple values: `?action=&action=` - Null check: `?action=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/listmymoderationrecords?action=active // Get records with multiple enum values (use multiple parameters) GET /v1/listmymoderationrecords?action=active&action=pending // Get records without this field GET /v1/listmymoderationrecords?action=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listmymoderationrecords` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {userId:this.session.userId} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({userId:this.session.userId}), {"path":"services[1].businessLogic[30].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listmymoderationrecords` api has 1 filter parameter available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | action | Enum | No | Moderation action taken | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/listmymoderationrecords** ```js axios({ method: 'GET', url: '/v1/listmymoderationrecords', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // action: '' // Filter by action } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`moderationRecords`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "moderationRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "moderationRecords": [ { "id": "ID", "action": "Enum", "action_idx": "Integer", "offenseType": "String", "reason": "Text", "suspensionExpiresAt": "Date", "userId": "ID", "content": "String", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Banappeals` # Business API Design Specification - `List Banappeals` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listBanAppeals` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listBanAppeals` Business API is designed to handle a `list` operation on the `BanAppeals` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `banappeals-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listBanAppeals` Business API includes a REST controller that can be triggered via the following route: `/v1/banappealses` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listBanAppeals` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listBanAppeals` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `No` | `` | `query` | `userId` | | **Description:** | - | | | | | | | | | | | | | `status` | `ID` | `No` | `` | `query` | `status` | | **Description:** | - | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listBanAppeals` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[31].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listBanAppeals` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | false | request.query?.["userId"] | | status | ID | false | request.query?.["status"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/banappealses** ```js axios({ method: 'GET', url: '/v1/banappealses', data: { }, params: { userId:'"ID"', status:'"ID"', } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`banAppealses`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppealses", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "banAppealses": [ { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "showmoderationRecord": [ { "offenseType": "String", "reason": "Text", "userId": "ID", "content": "String" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Banappeal` # Business API Design Specification - `Create Banappeal` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createBanAppeal` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createBanAppeal` Business API is designed to handle a `create` operation on the `BanAppeals` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `banappeal-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createBanAppeal` Business API includes a REST controller that can be triggered via the following route: `/v1/banappeal` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createBanAppeal` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createBanAppeal` Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `banAppealsId` | `ID` | `No` | `-` | `body` | `banAppealsId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `moderationRecordId` | `ID` | `Yes` | `-` | `body` | `moderationRecordId` | | **Description:** | id of the mod record | | | | | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `session` | `userId` | | **Description:** | | | | | | | | | | | | | | `appealReason` | `String` | `Yes` | `-` | `body` | `appealReason` | | **Description:** | | | | | | | | | | | | | | `status` | `Enum` | `Yes` | `-` | `body` | `status` | | **Description:** | | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createBanAppeal` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** ```js { status: runMScript(() => ('pending'), {"path":"services[1].businessLogic[32].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.banAppealsId, moderationRecordId: this.moderationRecordId, userId: this.userId, appealReason: this.appealReason, status: runMScript(() => ('pending'), {"path":"services[1].businessLogic[32].dataClause.customData[0].value"}), isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createBanAppeal` api has got 3 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | moderationRecordId | ID | true | request.body?.["moderationRecordId"] | | appealReason | String | true | request.body?.["appealReason"] | | status | Enum | true | request.body?.["status"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/banappeal** ```js axios({ method: 'POST', url: '/v1/banappeal', data: { moderationRecordId:"ID", appealReason:"String", status:"Enum", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`banAppeals`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppeals", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "banAppeals": { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Banappeal` # Business API Design Specification - `Update Banappeal` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateBanAppeal` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateBanAppeal` Business API is designed to handle a `update` operation on the `BanAppeals` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `banappeal-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateBanAppeal` Business API includes a REST controller that can be triggered via the following route: `/v1/banappeal/:banAppealsId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateBanAppeal` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateBanAppeal` Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `banAppealsId` | `ID` | `Yes` | `-` | `urlpath` | `banAppealsId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `status` | `Enum` | `Yes` | `` | `body` | `status` | | **Description:** | - | | | | | | | | | | | | | `moderationRecordId` | `ID` | `No` | `-` | `body` | `moderationRecordId` | | **Description:** | id of the mod record | | | | | | | | | | | | | `userId` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | | | | | | | | | | | | | | `appealReason` | `String` | `No` | `-` | `body` | `appealReason` | | **Description:** | | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateBanAppeal` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superAdmin`, `admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.banAppealsId},{isActive:true}]}), {"path":"services[1].businessLogic[33].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[33].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { moderationRecordId: this.moderationRecordId, userId: this.userId, appealReason: this.appealReason, status: runMScript(() => (this.status), {"path":"services[1].businessLogic[33].dataClause.customData[0].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateBanAppeal` api has got 4 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | banAppealsId | ID | true | request.params?.["banAppealsId"] | | status | Enum | true | request.body?.["status"] | | moderationRecordId | ID | false | request.body?.["moderationRecordId"] | | appealReason | String | false | request.body?.["appealReason"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/banappeal/:banAppealsId** ```js axios({ method: 'PATCH', url: `/v1/banappeal/${banAppealsId}`, data: { status:"Enum", moderationRecordId:"ID", appealReason:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`banAppeals`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "banAppeals", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "banAppeals": { "id": "ID", "moderationRecordId": "ID", "userId": "ID", "appealReason": "String", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Create Additionalquota` # Business API Design Specification - `Create Additionalquota` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createAdditionalQuota` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createAdditionalQuota` Business API is designed to handle a `create` operation on the `AdditionalQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquota-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createAdditionalQuota` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalquotas` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createAdditionalQuota` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAdditionalQuota` Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `additionalQuotaId` | `ID` | `No` | `-` | `body` | `additionalQuotaId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `userId` | `String` | `Yes` | `-` | `session` | `userId` | | **Description:** | | | | | | | | | | | | | | `additionalMessage` | `Integer` | `Yes` | `-` | `body` | `additionalMessage` | | **Description:** | | | | | | | | | | | | | | `status` | `Enum` | `Yes` | `-` | `body` | `status` | | **Description:** | | | | | | | | | | | | | | `currency` | `String` | `Yes` | `-` | `body` | `currency` | | **Description:** | | | | | | | | | | | | | | `pricePaid` | `Integer` | `Yes` | `-` | `body` | `pricePaid` | | **Description:** | | | | | | | | | | | | | | `statusUpdatedAt` | `Date` | `No` | `-` | `body` | `statusUpdatedAt` | | **Description:** | | | | | | | | | | | | | | `activatedAt` | `Date` | `No` | `-` | `body` | `activatedAt` | | **Description:** | | | | | | | | | | | | | | `cancelledAt` | `Date` | `No` | `-` | `body` | `cancelledAt` | | **Description:** | | | | | | | | | | | | | | `periodEnd` | `Date` | `No` | `-` | `body` | `periodEnd` | | **Description:** | | | | | | | | | | | | | | `periodStart` | `Date` | `No` | `-` | `body` | `periodStart` | | **Description:** | | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createAdditionalQuota` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** ```js { status: runMScript(() => ('pending'), {"path":"services[1].businessLogic[34].dataClause.customData[0].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.additionalQuotaId, userId: this.userId, additionalMessage: this.additionalMessage, status: runMScript(() => ('pending'), {"path":"services[1].businessLogic[34].dataClause.customData[0].value"}), currency: this.currency, pricePaid: this.pricePaid, statusUpdatedAt: this.statusUpdatedAt, activatedAt: this.activatedAt, cancelledAt: this.cancelledAt, periodEnd: this.periodEnd, periodStart: this.periodStart, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createAdditionalQuota` api has got 9 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalMessage | Integer | true | request.body?.["additionalMessage"] | | status | Enum | true | request.body?.["status"] | | currency | String | true | request.body?.["currency"] | | pricePaid | Integer | true | request.body?.["pricePaid"] | | statusUpdatedAt | Date | false | request.body?.["statusUpdatedAt"] | | activatedAt | Date | false | request.body?.["activatedAt"] | | cancelledAt | Date | false | request.body?.["cancelledAt"] | | periodEnd | Date | false | request.body?.["periodEnd"] | | periodStart | Date | false | request.body?.["periodStart"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/additionalquotas** ```js axios({ method: 'POST', url: '/v1/additionalquotas', data: { additionalMessage:"Integer", status:"Enum", currency:"String", pricePaid:"Integer", statusUpdatedAt:"Date", activatedAt:"Date", cancelledAt:"Date", periodEnd:"Date", periodStart:"Date", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`additionalQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Myadditionalquota` # Business API Design Specification - `Get Myadditionalquota` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getMyAdditionalQuota` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getMyAdditionalQuota` Business API is designed to handle a `get` operation on the `AdditionalQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `myadditionalquota-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getMyAdditionalQuota` Business API includes a REST controller that can be triggered via the following route: `/v1/myadditionalquota` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getMyAdditionalQuota` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getMyAdditionalQuota` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getMyAdditionalQuota` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {status:'active'} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{status:'active'},{isActive:true}]}), {"path":"services[1].businessLogic[35].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Action : myaddQuota **Action Type**: `FunctionCallAction` myaddQuota ```js class Api { async myaddQuota() { try { return await runMScript( () => (async () => await LIB.fetchAdditionalQuota(this.session.userId))(), { path: "services[1].businessLogic[35].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction myaddQuota:", err); throw err; } } } ``` --- ### [11] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [12] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getMyAdditionalQuota` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/myadditionalquota** ```js axios({ method: 'GET', url: '/v1/myadditionalquota', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`additionalQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "myaddQuota": "Object" } ``` --- ### Business API Design Specification - `Get Additionalquotapayment` # Business API Design Specification - `Get Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getAdditionalQuotaPayment` Business API is designed to handle a `get` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment information by ID. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAdditionalQuotaPayment` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_additionalQuotaPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_additionalQuotaPaymentId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.sys_additionalQuotaPaymentId},{isActive:true}]}), {"path":"services[1].businessLogic[36].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getAdditionalQuotaPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'GET', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Additionalquotapayments` # Business API Design Specification - `List Additionalquotapayments` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listAdditionalQuotaPayments` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listAdditionalQuotaPayments` Business API is designed to handle a `list` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to list all payments. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayments-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listAdditionalQuotaPayments` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalquotapayments` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listAdditionalQuotaPayments` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAdditionalQuotaPayments` Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listAdditionalQuotaPayments` api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `ownerId` Filter **Type:** `ID` **Description:** An ID value to represent owner user who created the order **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?ownerId=` - Multiple values: `?ownerId=&ownerId=` - Null check: `?ownerId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/additionalquotapayments?ownerId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/additionalquotapayments?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/additionalquotapayments?ownerId=null ``` #### `orderId` Filter **Type:** `ID` **Description:** an ID value to represent the orderId which is the ID parameter of the source additionalQuota object **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?orderId=` - Multiple values: `?orderId=&orderId=` - Null check: `?orderId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/additionalquotapayments?orderId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/additionalquotapayments?orderId=550e8400-e29b-41d4-a716-446655440000&orderId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/additionalquotapayments?orderId=null ``` #### `paymentId` Filter **Type:** `String` **Description:** 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 **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?paymentId=` (matches any string containing the value, case-insensitive) - Multiple values: `?paymentId=&paymentId=` (matches records containing any of the values) - Null check: `?paymentId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/additionalquotapayments?paymentId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/additionalquotapayments?paymentId=laptop&paymentId=phone&paymentId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/additionalquotapayments?paymentId=null ``` #### `paymentStatus` Filter **Type:** `String` **Description:** A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?paymentStatus=` (matches any string containing the value, case-insensitive) - Multiple values: `?paymentStatus=&paymentStatus=` (matches records containing any of the values) - Null check: `?paymentStatus=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/additionalquotapayments?paymentStatus=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/additionalquotapayments?paymentStatus=laptop&paymentStatus=phone&paymentStatus=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/additionalquotapayments?paymentStatus=null ``` #### `statusLiteral` Filter **Type:** `String` **Description:** A string value to represent the logical payment status which belongs to the application lifecycle itself. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?statusLiteral=` (matches any string containing the value, case-insensitive) - Multiple values: `?statusLiteral=&statusLiteral=` (matches records containing any of the values) - Null check: `?statusLiteral=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/additionalquotapayments?statusLiteral=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/additionalquotapayments?statusLiteral=laptop&statusLiteral=phone&statusLiteral=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/additionalquotapayments?statusLiteral=null ``` #### `redirectUrl` Filter **Type:** `String` **Description:** 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. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?redirectUrl=` (matches any string containing the value, case-insensitive) - Multiple values: `?redirectUrl=&redirectUrl=` (matches records containing any of the values) - Null check: `?redirectUrl=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/additionalquotapayments?redirectUrl=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/additionalquotapayments?redirectUrl=laptop&redirectUrl=phone&redirectUrl=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/additionalquotapayments?redirectUrl=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listAdditionalQuotaPayments` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[37].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listAdditionalQuotaPayments` api has 6 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | ownerId | ID | No | An ID value to represent owner user who created the order | | orderId | ID | No | an ID value to represent the orderId which is the ID parameter of the source additionalQuota object | | paymentId | String | No | 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 | No | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | statusLiteral | String | No | 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. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/additionalquotapayments** ```js axios({ method: 'GET', url: '/v1/additionalquotapayments', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayments`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_additionalQuotaPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Additionalquotapayment` # Business API Design Specification - `Create Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createAdditionalQuotaPayment` Business API is designed to handle a `create` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to create a new payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalquotapayment` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAdditionalQuotaPayment` Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_additionalQuotaPaymentId` | `ID` | `No` | `-` | `body` | `sys_additionalQuotaPaymentId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `ownerId` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | An ID value to represent owner user who created the order | | | | | | | | | | | | | `orderId` | `ID` | `Yes` | `-` | `body` | `orderId` | | **Description:** | an ID value to represent the orderId which is the ID parameter of the source additionalQuota object | | | | | | | | | | | | | `paymentId` | `String` | `Yes` | `-` | `body` | `paymentId` | | **Description:** | 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` | `-` | `body` | `paymentStatus` | | **Description:** | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | | | | | | | | | | | | `statusLiteral` | `String` | `Yes` | `-` | `body` | `statusLiteral` | | **Description:** | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | | | | | | | | | | | | `redirectUrl` | `String` | `No` | `-` | `body` | `redirectUrl` | | **Description:** | 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. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.sys_additionalQuotaPaymentId, ownerId: this.ownerId, orderId: this.orderId, paymentId: this.paymentId, paymentStatus: this.paymentStatus, statusLiteral: this.statusLiteral, redirectUrl: this.redirectUrl, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createAdditionalQuotaPayment` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/additionalquotapayment** ```js axios({ method: 'POST', url: '/v1/additionalquotapayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Additionalquotapayment` # Business API Design Specification - `Update Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateAdditionalQuotaPayment` Business API is designed to handle a `update` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to update an existing payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateAdditionalQuotaPayment` Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_additionalQuotaPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_additionalQuotaPaymentId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `ownerId` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | An ID value to represent owner user who created the order | | | | | | | | | | | | | `paymentId` | `String` | `No` | `-` | `body` | `paymentId` | | **Description:** | 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` | `No` | `-` | `body` | `paymentStatus` | | **Description:** | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | | | | | | | | | | | | `statusLiteral` | `String` | `No` | `-` | `body` | `statusLiteral` | | **Description:** | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | | | | | | | | | | | | `redirectUrl` | `String` | `No` | `-` | `body` | `redirectUrl` | | **Description:** | 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. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.sys_additionalQuotaPaymentId},{isActive:true}]}), {"path":"services[1].businessLogic[39].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { ownerId: this.ownerId, paymentId: this.paymentId, paymentStatus: this.paymentStatus, statusLiteral: this.statusLiteral, redirectUrl: this.redirectUrl, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateAdditionalQuotaPayment` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'PATCH', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Additionalquotapayment` # Business API Design Specification - `Delete Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deleteAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deleteAdditionalQuotaPayment` Business API is designed to handle a `delete` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to delete a payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deleteAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalquotapayment/:sys_additionalQuotaPaymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deleteAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteAdditionalQuotaPayment` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_additionalQuotaPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_additionalQuotaPaymentId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deleteAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.sys_additionalQuotaPaymentId},{isActive:true}]}), {"path":"services[1].businessLogic[40].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deleteAdditionalQuotaPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_additionalQuotaPaymentId | ID | true | request.params?.["sys_additionalQuotaPaymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/additionalquotapayment/:sys_additionalQuotaPaymentId** ```js axios({ method: 'DELETE', url: `/v1/additionalquotapayment/${sys_additionalQuotaPaymentId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Additionalquotapaymentbyorderid` # Business API Design Specification - `Get Additionalquotapaymentbyorderid` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getAdditionalQuotaPaymentByOrderId` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getAdditionalQuotaPaymentByOrderId` Business API is designed to handle a `get` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment information by order id. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapaymentbyorderid-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getAdditionalQuotaPaymentByOrderId` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalQuotapaymentbyorderid/:orderId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getAdditionalQuotaPaymentByOrderId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAdditionalQuotaPaymentByOrderId` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `orderId` | `ID` | `Yes` | `-` | `urlpath` | `orderId` | | **Description:** | an ID value to represent the orderId which is the ID parameter of the source additionalQuota object. The parameter is used to query data. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getAdditionalQuotaPaymentByOrderId` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{orderId:{"$eq":this.orderId}},{isActive:true}]}), {"path":"services[1].businessLogic[41].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getAdditionalQuotaPaymentByOrderId` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/additionalQuotapaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/additionalQuotapaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Additionalquotapaymentbypaymentid` # Business API Design Specification - `Get Additionalquotapaymentbypaymentid` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getAdditionalQuotaPaymentByPaymentId` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getAdditionalQuotaPaymentByPaymentId` Business API is designed to handle a `get` operation on the `Sys_additionalQuotaPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment information by payment id. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapaymentbypaymentid-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getAdditionalQuotaPaymentByPaymentId` Business API includes a REST controller that can be triggered via the following route: `/v1/additionalQuotapaymentbypaymentid/:paymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getAdditionalQuotaPaymentByPaymentId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAdditionalQuotaPaymentByPaymentId` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `paymentId` | `String` | `Yes` | `-` | `urlpath` | `paymentId` | | **Description:** | 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. The parameter is used to query data. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getAdditionalQuotaPaymentByPaymentId` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{paymentId:{"$eq":this.paymentId}},{isActive:true}]}), {"path":"services[1].businessLogic[42].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getAdditionalQuotaPaymentByPaymentId` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/additionalQuotapaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/additionalQuotapaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_additionalQuotaPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_additionalQuotaPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_additionalQuotaPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Start Additionalquotapayment` # Business API Design Specification - `Start Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `startAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `startAdditionalQuotaPayment` Business API is designed to handle a `update` operation on the `AdditionalQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Start payment for additionalQuota ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-started` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `startAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/startadditionalquotapayment/:additionalQuotaId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `startAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `startAdditionalQuotaPayment` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `additionalQuotaId` | `ID` | `Yes` | `-` | `urlpath` | `additionalQuotaId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `paymentUserParams` | `Object` | `Yes` | `-` | `body` | `paymentUserParams` | | **Description:** | The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `startAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.additionalQuotaId},{isActive:true}]}), {"path":"services[1].businessLogic[43].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[43].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[1].businessLogic[43].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[1].businessLogic[43].dataClause.customData[2].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[43].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[1].businessLogic[43].dataClause.customData[1].value"}), // paymentConfirmation parameter is closed to update by client request // include it in data clause unless you are sure paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[1].businessLogic[43].dataClause.customData[2].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Action : checkPaymentMethodId **Action Type**: `ValidationAction` Validate that paymentMethodId is provided in paymentUserParams ```js class Api { async checkPaymentMethodId() { const isValid = runMScript( () => !!this.paymentUserParams?.paymentMethodId, { path: "services[1].businessLogic[43].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError( "paymentUserParams.paymentMethodId is required to start a payment", ); } return isValid; } } ``` --- ### [6] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [7] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [8] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [9] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [10] Action : doStartPayment **Action Type**: `PaymentAction` Start a payment on Stripe platform ```js class Api { getOrderId() { return this.additionalQuotaId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "appaili-aicoach-service-additionalquotapaymentstatus-started"; case "updated": return "appaili-aicoach-service-additionalquotapaymentstatus-updated"; case "succeeded": return "appaili-aicoach-service-additionalquotapaymentstatus-succeeded"; case "failed": return "appaili-aicoach-service-additionalquotapaymentstatus-failed"; case "paymentdone": return "appaili-aicoach-service-additionalquota-paymentdone"; } } async paymentUpdated(statusLiteral) { switch (statusLiteral) { case "started": await this.paymentStarted(); break; case "canceled": await this.paymentCanceled(); break; case "failed": await this.paymentFailed(); break; case "success": await this.paymentDone(); break; default: await this.paymentFailed(); break; } } async paymentStarted() { this.status = runMScript(() => "pending", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.status = runMScript(() => "cancelled", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.status = runMScript(() => "failed", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.status = runMScript(() => "active", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript(() => "additionalquota addition", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.description", }); const metadata = { order: "AiCoach-AdditionalQuota-order", orderId: this.additionalQuota.id, paymentName: "additionalQuota", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.additionalQuota.pricePaid, currency: this.additionalQuota.currency, orderId: this.additionalQuota.id, metadata: metadata, storeCard: userParams?.storeCard, paymentUserParams: userParams, bodyParams: this.bodyParams, }; } async doStartPayment() { // Handle Payment Action try { if (!this.paymentManager) { throw new Error( "This dboject is not an order object. So auto-payment process can not be started.", ); } this.paymentResult = await this.paymentManager.startPayment( this.paymentUserParams, ); } catch (err) { if (err instanceof PaymentGateError) { this.paymentResult = err.serializeError(); //**errorLog } else throw err; } return this.paymentResult; } } ``` --- ### [11] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [12] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [13] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [14] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [15] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `startAdditionalQuotaPayment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/startadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/startadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`additionalQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` --- ### Business API Design Specification - `Refresh Additionalquotapayment` # Business API Design Specification - `Refresh Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `refreshAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `refreshAdditionalQuotaPayment` Business API is designed to handle a `update` operation on the `AdditionalQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Refresh payment info for additionalQuota from Stripe ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-refreshed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `refreshAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/refreshadditionalquotapayment/:additionalQuotaId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `refreshAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `refreshAdditionalQuotaPayment` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `additionalQuotaId` | `ID` | `Yes` | `-` | `urlpath` | `additionalQuotaId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `paymentUserParams` | `Object` | `No` | `-` | `body` | `paymentUserParams` | | **Description:** | The user parameters that should be defined to refresh a stripe payment process | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `refreshAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.additionalQuotaId},{isActive:true}]}), {"path":"services[1].businessLogic[44].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[44].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[1].businessLogic[44].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[1].businessLogic[44].dataClause.customData[2].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[44].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[1].businessLogic[44].dataClause.customData[1].value"}), // paymentConfirmation parameter is closed to update by client request // include it in data clause unless you are sure paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[1].businessLogic[44].dataClause.customData[2].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Action : doRefreshPayment **Action Type**: `PaymentAction` Refresh payment from Stripe platform, the payment operation data in the gateway server will be fetched and the application payment tickets and order status will be refreshed according to the server. This api may be used if you dont want to use a webhook. ```js class Api { getOrderId() { return this.additionalQuotaId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "appaili-aicoach-service-additionalquotapaymentstatus-started"; case "updated": return "appaili-aicoach-service-additionalquotapaymentstatus-updated"; case "succeeded": return "appaili-aicoach-service-additionalquotapaymentstatus-succeeded"; case "failed": return "appaili-aicoach-service-additionalquotapaymentstatus-failed"; case "paymentdone": return "appaili-aicoach-service-additionalquota-paymentdone"; } } async paymentUpdated(statusLiteral) { switch (statusLiteral) { case "started": await this.paymentStarted(); break; case "canceled": await this.paymentCanceled(); break; case "failed": await this.paymentFailed(); break; case "success": await this.paymentDone(); break; default: await this.paymentFailed(); break; } } async paymentStarted() { this.status = runMScript(() => "pending", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.status = runMScript(() => "cancelled", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.status = runMScript(() => "failed", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.status = runMScript(() => "active", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript(() => "additionalquota addition", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.description", }); const metadata = { order: "AiCoach-AdditionalQuota-order", orderId: this.additionalQuota.id, paymentName: "additionalQuota", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.additionalQuota.pricePaid, currency: this.additionalQuota.currency, orderId: this.additionalQuota.id, metadata: metadata, storeCard: userParams?.storeCard, paymentUserParams: userParams, bodyParams: this.bodyParams, }; } async doRefreshPayment() { // Handle Payment Action try { if (!this.paymentManager) { throw new Error( "This dboject is not an order object. So auto-payment process can not be started.", ); } this.paymentResult = await this.paymentManager.refreshPayment( this.paymentUserParams, ); } catch (err) { if (err instanceof PaymentGateError) { this.paymentResult = err.serializeError(); //**errorLog } else throw err; } return this.paymentResult; } } ``` --- ### [10] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [11] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [12] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [13] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [14] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `refreshAdditionalQuotaPayment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | true | request.params?.["additionalQuotaId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/refreshadditionalquotapayment/:additionalQuotaId** ```js axios({ method: 'PATCH', url: `/v1/refreshadditionalquotapayment/${additionalQuotaId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`additionalQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` --- ### Business API Design Specification - `Callback Additionalquotapayment` # Business API Design Specification - `Callback Additionalquotapayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `callbackAdditionalQuotaPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `callbackAdditionalQuotaPayment` Business API is designed to handle a `update` operation on the `AdditionalQuota` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Refresh payment values by gateway webhook call for additionalQuota ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `additionalquotapayment-calledback` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `callbackAdditionalQuotaPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/callbackadditionalquotapayment` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `callbackAdditionalQuotaPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `callbackAdditionalQuotaPayment` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `additionalQuotaId` | `ID` | `No` | `-` | `body` | `additionalQuotaId` | | **Description:** | The order id parameter that will be read from webhook callback params | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. * `additionalQuotaId`: ```javascript this.additionalQuotaId = runMScript(() => (this.paymentCallbackParams?.orderId), {"path":"services[1].businessLogic[45].customParameters[0].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `callbackAdditionalQuotaPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API is **public** and can be accessed without login (`loginRequired = false`). --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.additionalQuotaId},{isActive:true}]}), {"path":"services[1].businessLogic[45].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[45].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[1].businessLogic[45].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[1].businessLogic[45].dataClause.customData[2].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { status: runMScript(() => (this.status), {"path":"services[1].businessLogic[45].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[1].businessLogic[45].dataClause.customData[1].value"}), // paymentConfirmation parameter is closed to update by client request // include it in data clause unless you are sure paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[1].businessLogic[45].dataClause.customData[2].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : verifyPaymentWebhook **Action Type**: `VerifyWebhookAction` Verify a providers webhook call with the secret signature and read the params, write the callback parameters to the context. Only stripe webhooks is supported for now. ```js class Api { // Code for VerifyWebhookAction async verifyPaymentWebhook() { const secretKey = runMScript(() => process.env.STRIPE_WEBHOOK_SECRET, { path: "services[1].businessLogic[45].actions.verifyWebhookActions[0].secretKey", }); await this.paymentManager.ensurePaymentGate(); const stripeGateway = this.paymentManager.paymentGate; const result = await stripeGateway.webhookController(this.request); console.log("VerifyWebhookAction result -->", result); if (result.statusLiteral == "unhandled") { throw new BadRequestError( `Unhandled stripe webhook event [${result.eventType}]`, ); } return result; } } ``` --- ### [4] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [5] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [6] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [7] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [8] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [9] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [10] Action : doPaymentCallback **Action Type**: `PaymentAction` Refresh payment by Stripe platform webhook, the payment operation data in the gateway server will be given by webhook call and the application payment tickets and order status will be refreshed according to the server. ```js class Api { getOrderId() { return this.additionalQuotaId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "appaili-aicoach-service-additionalquotapaymentstatus-started"; case "updated": return "appaili-aicoach-service-additionalquotapaymentstatus-updated"; case "succeeded": return "appaili-aicoach-service-additionalquotapaymentstatus-succeeded"; case "failed": return "appaili-aicoach-service-additionalquotapaymentstatus-failed"; case "paymentdone": return "appaili-aicoach-service-additionalquota-paymentdone"; } } async paymentUpdated(statusLiteral) { switch (statusLiteral) { case "started": await this.paymentStarted(); break; case "canceled": await this.paymentCanceled(); break; case "failed": await this.paymentFailed(); break; case "success": await this.paymentDone(); break; default: await this.paymentFailed(); break; } } async paymentStarted() { this.status = runMScript(() => "pending", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.status = runMScript(() => "cancelled", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.status = runMScript(() => "failed", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.status = runMScript(() => "active", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript(() => "additionalquota addition", { path: "services[1].dataObjects[11].objectSettings.stripeOrder.configuration.description", }); const metadata = { order: "AiCoach-AdditionalQuota-order", orderId: this.additionalQuota.id, paymentName: "additionalQuota", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.additionalQuota.pricePaid, currency: this.additionalQuota.currency, orderId: this.additionalQuota.id, metadata: metadata, storeCard: userParams?.storeCard, paymentUserParams: userParams, bodyParams: this.bodyParams, }; } async doPaymentCallback() { // Handle Payment Action try { if (!this.paymentManager) { throw new Error( "This dboject is not an order object. So auto-payment process can not be started.", ); } this.paymentResult = await this.paymentManager.processPaymentCallbackResult( this.paymentCallbackParams, ); } catch (err) { if (err instanceof PaymentGateError) { this.paymentResult = err.serializeError(); //**errorLog } else throw err; } return this.paymentResult; } } ``` --- ### [11] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [12] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [13] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [14] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [15] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `callbackAdditionalQuotaPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | additionalQuotaId | ID | false | request.body?.["additionalQuotaId"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/callbackadditionalquotapayment** ```js axios({ method: 'POST', url: '/v1/callbackadditionalquotapayment', data: { additionalQuotaId:"ID", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`additionalQuota`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "additionalQuota", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "additionalQuota": { "id": "ID", "userId": "String", "additionalMessage": "Integer", "status": "Enum", "status_idx": "Integer", "currency": "String", "pricePaid": "Integer", "statusUpdatedAt": "Date", "activatedAt": "Date", "cancelledAt": "Date", "periodEnd": "Date", "periodStart": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` --- ### Business API Design Specification - `Get Paymentcustomerbyuserid` # Business API Design Specification - `Get Paymentcustomerbyuserid` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getPaymentCustomerByUserId` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getPaymentCustomerByUserId` Business API is designed to handle a `get` operation on the `Sys_paymentCustomer` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment customer information by user id. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `paymentcustomerbyuserid-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getPaymentCustomerByUserId` Business API includes a REST controller that can be triggered via the following route: `/v1/paymentcustomers/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getPaymentCustomerByUserId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getPaymentCustomerByUserId` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getPaymentCustomerByUserId` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId:{"$eq":this.userId}},{isActive:true}]}), {"path":"services[1].businessLogic[46].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getPaymentCustomerByUserId` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_paymentCustomer`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Paymentcustomers` # Business API Design Specification - `List Paymentcustomers` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listPaymentCustomers` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listPaymentCustomers` Business API is designed to handle a `list` operation on the `Sys_paymentCustomer` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to list all payment customers. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `paymentcustomers-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listPaymentCustomers` Business API includes a REST controller that can be triggered via the following route: `/v1/paymentcustomers` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listPaymentCustomers` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPaymentCustomers` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `userId` Filter **Type:** `ID` **Description:** An ID value to represent the user who is created as a stripe customer **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/paymentcustomers?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/paymentcustomers?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/paymentcustomers?userId=null ``` #### `customerId` Filter **Type:** `String` **Description:** 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 **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?customerId=` (matches any string containing the value, case-insensitive) - Multiple values: `?customerId=&customerId=` (matches records containing any of the values) - Null check: `?customerId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomers?customerId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomers?customerId=laptop&customerId=phone&customerId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomers?customerId=null ``` #### `platform` Filter **Type:** `String` **Description:** 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. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?platform=` (matches any string containing the value, case-insensitive) - Multiple values: `?platform=&platform=` (matches records containing any of the values) - Null check: `?platform=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomers?platform=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomers?platform=laptop&platform=phone&platform=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomers?platform=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listPaymentCustomers` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[47].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listPaymentCustomers` api has 3 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | userId | ID | No | An ID value to represent the user who is created as a stripe customer | | customerId | String | No | 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 | No | 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. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_paymentCustomers`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Paymentcustomermethods` # Business API Design Specification - `List Paymentcustomermethods` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listPaymentCustomerMethods` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listPaymentCustomerMethods` Business API is designed to handle a `list` operation on the `Sys_paymentMethod` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to list all payment customer methods. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `paymentcustomermethods-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listPaymentCustomerMethods` Business API includes a REST controller that can be triggered via the following route: `/v1/paymentcustomermethods/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listPaymentCustomerMethods` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPaymentCustomerMethods` Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | An ID value to represent the user who owns the payment method. The parameter is used to query data. | | | | | | | | | | | | ### Filter Parameters The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `paymentMethodId` Filter **Type:** `String` **Description:** A string value to represent the id of the payment method on the payment platform. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?paymentMethodId=` (matches any string containing the value, case-insensitive) - Multiple values: `?paymentMethodId=&paymentMethodId=` (matches records containing any of the values) - Null check: `?paymentMethodId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?paymentMethodId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?paymentMethodId=laptop&paymentMethodId=phone&paymentMethodId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?paymentMethodId=null ``` #### `customerId` Filter **Type:** `String` **Description:** A string value to represent the customer id which is generated on the payment gateway. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?customerId=` (matches any string containing the value, case-insensitive) - Multiple values: `?customerId=&customerId=` (matches records containing any of the values) - Null check: `?customerId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?customerId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?customerId=laptop&customerId=phone&customerId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?customerId=null ``` #### `cardHolderName` Filter **Type:** `String` **Description:** A string value to represent the name of the card holder. It can be different than the registered customer. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?cardHolderName=` (matches any string containing the value, case-insensitive) - Multiple values: `?cardHolderName=&cardHolderName=` (matches records containing any of the values) - Null check: `?cardHolderName=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?cardHolderName=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?cardHolderName=laptop&cardHolderName=phone&cardHolderName=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?cardHolderName=null ``` #### `cardHolderZip` Filter **Type:** `String` **Description:** A string value to represent the zip code of the card holder. It is used for address verification in specific countries. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?cardHolderZip=` (matches any string containing the value, case-insensitive) - Multiple values: `?cardHolderZip=&cardHolderZip=` (matches records containing any of the values) - Null check: `?cardHolderZip=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?cardHolderZip=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?cardHolderZip=laptop&cardHolderZip=phone&cardHolderZip=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?cardHolderZip=null ``` #### `platform` Filter **Type:** `String` **Description:** 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. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?platform=` (matches any string containing the value, case-insensitive) - Multiple values: `?platform=&platform=` (matches records containing any of the values) - Null check: `?platform=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?platform=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?platform=laptop&platform=phone&platform=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?platform=null ``` #### `cardInfo` Filter **Type:** `Object` **Description:** A Json value to store the card details of the payment method. **Location:** Query Parameter **Usage:** - Single value: `?cardInfo=` - Multiple values: `?cardInfo=&cardInfo=` - Null check: `?cardInfo=null` **Examples:** ```javascript // Get records with specific value GET /v1/paymentcustomermethods/:userId?cardInfo= // Get records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?cardInfo=&cardInfo= // Get records without this field GET /v1/paymentcustomermethods/:userId?cardInfo=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listPaymentCustomerMethods` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId:{"$eq":this.userId}},{isActive:true}]}), {"path":"services[1].businessLogic[48].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listPaymentCustomerMethods` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | The `listPaymentCustomerMethods` api has 6 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | paymentMethodId | String | No | A string value to represent the id of the payment method on the payment platform. | | customerId | String | No | 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 | No | 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 | No | A Json value to store the card details of the payment method. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_paymentMethods`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ## Service Library - `aiCoach` # Service Library - `aiCoach` This document provides a complete reference of the custom code library for the `aiCoach` service. It includes all library functions, edge functions with their REST endpoints, templates, and assets. ## Library Functions Library functions are reusable modules available to all business APIs and other custom code within the service via `require("lib/")`. ### `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 Edge functions are custom HTTP endpoint handlers that run outside the standard Business API pipeline. Each edge function is paired with an Edge Controller that defines its REST endpoint. ### `reverseBanFn.js` **Edge Controller:** - **Path:** `/admin/reverse-ban` - **Method:** `GET` - **Login Required:** No ```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` **Edge Controller:** - **Path:** `/admin/usage-analytics` - **Method:** `GET` - **Login Required:** No ```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 }; } }; ``` ## Edge Controllers Summary | Function Name | Method | Path | Login Required | |--------------|--------|------|----------------| | `getUsageAnalyticsFn` | `GET` | `/admin/usage-analytics` | No | | `reverseBanFn` | `GET` | `/admin/reverse-ban` | No | --- *This document was generated from the service library configuration and should be kept in sync with design changes.* --- # Subscription Service ## Service Design Specification # Service Design Specification **aifitapp-subscription-service** documentation **Version:** `1.0.24` ## Scope This document provides a structured architectural overview of the `subscription` 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. ## `Subscription` Service Settings Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z ### 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-subscription-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://appaili.prw.mindbricks.com/subscription-api` * **Staging:** `https://appaili-stage.mindbricks.co/subscription-api` * **Production:** `https://appaili.mindbricks.co/subscription-api` ### Authentication & Security - **Login Required**: Yes This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `aifitapp-subscription-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 | |-------------|-------------|---------------| | `pricingConfig` | Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record. | accessProtected | | `subscription` | Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates. | accessPrivate | | `sys_subscriptionPayment` | A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object'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 | ## pricingConfig Data Object ### Object Overview **Description:** Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record. 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. ### Redis Entity Caching This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster. ### Properties Schema **Display Label Property:** `description` — 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 | |----------|------|----------|-------------| | `currency` | String | Yes | Currency code for pricing (e.g., usd). | | `description` | Text | No | Human-readable description of the subscription plan. | | `price` | Integer | Yes | Current subscription price in cents (e.g., 999 = $9.99). | | `type` | 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. - **currency**: usd - **description**: Premium Subscription - AI Fitness & Nutrition Coach - **price**: 0 - **type**: subscription ### Auto Update Properties `currency` `description` `price` `type` 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. - **type**: [subscription, quota] ### Elastic Search Indexing `currency` `description` `price` `type` 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 `type` 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. ## subscription Data Object ### Object Overview **Description:** Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates. 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 `subscription`. 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**: `subscription` - **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**: 'Premium Subscription - AI Fitness & Nutrition Coach' 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 `'pending'` and will be set to `status`property. `paymentResultCanceled` status will be mapped to a local value using `'cancelled'` and will be set to `status` property. `paymentResultFailed` status will be mapped to a local value using `'failed'` and will be set to `status` property. `paymentResultSuccess` status will be mapped to a local value using `'active'` 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 | |----------|------|----------|-------------| | `activatedAt` | Date | No | Timestamp when the subscription was activated after successful payment. | | `cancelledAt` | Date | No | Timestamp when the subscription was cancelled by the user. | | `currency` | String | Yes | Currency code for the payment (e.g., usd). | | `pricePaid` | Integer | Yes | Amount paid in cents at the time of subscription activation. | | `status` | Enum | No | Current subscription status managed by Stripe payment flow. | | `statusUpdatedAt` | Date | No | Timestamp of the last status update, auto-managed by Stripe payment flow. | | `userId` | ID | Yes | Reference to the user who owns this subscription. | | `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. - **currency**: usd - **pricePaid**: 0 - **status**: pending - **userId**: '00000000-0000-0000-0000-000000000000' - **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. - **status**: Will be created with value `pending` - **paymentConfirmation**: Will be created with value `pending` ### Constant Properties `currency` `pricePaid` `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`. ### 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, active, cancelled, expired, failed] - **paymentConfirmation**: [pending, processing, paid, canceled] ### Elastic Search Indexing `activatedAt` `cancelledAt` `currency` `pricePaid` `status` `statusUpdatedAt` `userId` `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 `status` `userId` `paymentConfirmation` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Secondary Key Properties `paymentConfirmation` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Relation Properties `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` `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. - **status**: Enum has a filter named `status` - **userId**: ID has a filter named `userId` - **paymentConfirmation**: Enum has a filter named `paymentConfirmation` ## sys_subscriptionPayment Data Object ### Object Overview **Description:** A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object'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 subscription 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 subscription has got 25 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Cancel Subscription](/document/businessLogic/cancelsubscription) * [Check Subscriptionstatus](/document/businessLogic/checksubscriptionstatus) * [Create Pricingconfig](/document/businessLogic/createpricingconfig) * [Delete Pricingconfig](/document/businessLogic/deletepricingconfig) * [Get Mysubscription](/document/businessLogic/getmysubscription) * [Get Pricingconfig](/document/businessLogic/getpricingconfig) * [Get Subscription](/document/businessLogic/getsubscription) * [List Pricingconfigs](/document/businessLogic/listpricingconfigs) * [List Subscriptions](/document/businessLogic/listsubscriptions) * [Update Pricingconfig](/document/businessLogic/updatepricingconfig) * [Create Subscription](/document/businessLogic/createsubscription) * [Do Test](/document/businessLogic/test) * [Get Subscriptionpayment](/document/businessLogic/getsubscriptionpayment) * [List Subscriptionpayments](/document/businessLogic/listsubscriptionpayments) * [Create Subscriptionpayment](/document/businessLogic/createsubscriptionpayment) * [Update Subscriptionpayment](/document/businessLogic/updatesubscriptionpayment) * [Delete Subscriptionpayment](/document/businessLogic/deletesubscriptionpayment) * [Get Subscriptionpaymentbyorderid](/document/businessLogic/getsubscriptionpaymentbyorderid) * [Get Subscriptionpaymentbypaymentid](/document/businessLogic/getsubscriptionpaymentbypaymentid) * [Start Subscriptionpayment](/document/businessLogic/startsubscriptionpayment) * [Refresh Subscriptionpayment](/document/businessLogic/refreshsubscriptionpayment) * [Callback Subscriptionpayment](/document/businessLogic/callbacksubscriptionpayment) * [Get Paymentcustomerbyuserid](/document/businessLogic/getpaymentcustomerbyuserid) * [List Paymentcustomers](/document/businessLogic/listpaymentcustomers) * [List Paymentcustomermethods](/document/businessLogic/listpaymentcustomermethods) ## Edge Controllers ### onPricingConfigCreated **Configuration:** - **Function Name**: `onPricingConfigCreated` - **Login Required**: No **REST Settings:** - **Path**: `/pricing-config-created` - **Method**: --- ### onPaymentDone **Configuration:** - **Function Name**: `onPaymentDone` - **Login Required**: No **REST Settings:** - **Path**: `` - **Method**: --- ## Service Library ### Edge Functions #### onPaymentDone.js ```js const { updateSubscriptionById } = require("dbLayer"); module.exports = async (request) => { const subscription = request.subscription; if (subscription && subscription.id) { await updateSubscriptionById(subscription.id, { activatedAt: new Date().toISOString() }); } return { status: 200, message: "Subscription activated successfully" }; }; ``` #### onPricingConfigCreated.js ```js const { fetchRemoteListByMQuery } = require("serviceCommon"); const axios = require("axios"); // HTML Email Template const getEmailHtml = (data) => { return `

Exciting News, ${data.userFullname}!

We're thrilled to announce a new premium plan option for AI Fitness & Nutrition Coach!

New Plan Details:

  • Price: ${(data.pricingAmount / 100).toFixed(2)} ${data.pricingCurrency.toUpperCase()}
  • Description: ${data.pricingDescription || 'Premium Subscription'}

With this premium subscription, you'll unlock:

  • Personalized Training Programs — Evidence-based workout routines tailored to your goals
  • Custom Nutrition Plans — Calorie and macro targets with regional meal suggestions
  • AI Fitness Coach Chatbot — Get real-time guidance, exercise substitutions, and food alternatives
  • Dynamic Program Adjustments — Your plans evolve as you progress
  • Weight Tracking & Optimization — Report your weight and let AI optimize your plan

Ready to take your fitness journey to the next level? Log in to your account and upgrade today!

Best regards,
The AI Fitness Coach Team

`; }; module.exports = async (request) => { try { // Get pricing config data from the Kafka event const pricingConfig = request.pricingConfig; if (!pricingConfig) { console.log("No pricing config data in event"); return { status: 200, message: "No pricing config data" }; } console.log(`New pricing config created: ${pricingConfig.id}`); // Fetch all users from auth service via Elasticsearch // Using empty query to get all users, with high limit const users = await fetchRemoteListByMQuery( "User", {}, // Empty query = all users 0, // from 1000, // size - adjust based on your user count [{ createdAt: { order: "desc" } }] ); console.log(`Found ${users.length} users to notify`); if (!users || users.length === 0) { return { status: 200, message: "No users found to notify" }; } // Get notification service URL from environment const notificationServiceUrl = process.env.NOTIFICATION_SERVICE_URL || "http://notification-service:3000"; // Send email to each user const emailPromises = users.map(async (user) => { try { const emailHtml = getEmailHtml({ userFullname: user.fullname, pricingAmount: pricingConfig.amount, pricingCurrency: pricingConfig.currency, pricingDescription: pricingConfig.description }); const notificationPayload = { types: ["email"], template: "NONE", // Use direct body instead of template to: user.email, isStored: false, title: "New Premium Plan Available!", body: emailHtml, metadata: { userFullname: user.fullname, pricingAmount: pricingConfig.amount, pricingCurrency: pricingConfig.currency, configId: pricingConfig.id } }; await axios.post( `${notificationServiceUrl}/notifications`, notificationPayload ); console.log(`Email sent to ${user.email}`); return { success: true, email: user.email }; } catch (error) { console.error(`Failed to send email to ${user.email}:`, error.message); return { success: false, email: user.email, error: error.message }; } }); const results = await Promise.allSettled(emailPromises); const successCount = results.filter(r => r.status === 'fulfilled' && r.value.success).length; const failCount = results.length - successCount; console.log(`Email broadcast complete: ${successCount} successful, ${failCount} failed`); return { status: 200, message: `Pricing config notification sent to ${successCount} users (${failCount} failed)`, totalUsers: users.length, successCount, failCount }; } catch (error) { console.error("Error in onPricingConfigCreated:", error); return { status: 500, message: "Error processing pricing config notification", error: error.message }; } }; ``` --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## aifitapp-subscription-service **Version:** `1.0.24` Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Subscription Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Subscription Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Subscription Service via HTTP requests for purposes such as creating, updating, deleting and querying Subscription objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the Subscription Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the Subscription service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | appaili-access-token| | Cookie | appaili-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the Subscription service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Subscription service. 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` This service is accessible via the following environment-specific URLs: * **Preview:** `https://appaili.prw.mindbricks.com/subscription-api` * **Staging:** `https://appaili-stage.mindbricks.co/subscription-api` * **Production:** `https://appaili.mindbricks.co/subscription-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the Subscription service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `Subscription` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Subscription` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `Subscription` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources Subscription service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### PricingConfig resource *Resource Definition* : Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record. *PricingConfig Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **currency** | String | | | *Currency code for pricing (e.g., usd).* | | **description** | Text | | | *Human-readable description of the subscription plan.* | | **price** | Integer | | | *Current subscription price in cents (e.g., 999 = $9.99).* | | **type** | Enum | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### type Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **subscription** | `"subscription""` | 0 | | **quota** | `"quota""` | 1 | ### Subscription resource *Resource Definition* : Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates. *Subscription Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **activatedAt** | Date | | | *Timestamp when the subscription was activated after successful payment.* | | **cancelledAt** | Date | | | *Timestamp when the subscription was cancelled by the user.* | | **currency** | String | | | *Currency code for the payment (e.g., usd).* | | **pricePaid** | Integer | | | *Amount paid in cents at the time of subscription activation.* | | **status** | Enum | | | *Current subscription status managed by Stripe payment flow.* | | **statusUpdatedAt** | Date | | | *Timestamp of the last status update, auto-managed by Stripe payment flow.* | | **userId** | ID | | | *Reference to the user who owns this subscription.* | | **paymentConfirmation** | Enum | | | *An automatic property that is used to check the confirmed status of the payment set by webhooks.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Property Definition* : Current subscription status managed by Stripe payment flow.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **active** | `"active""` | 1 | | **cancelled** | `"cancelled""` | 2 | | **expired** | `"expired""` | 3 | | **failed** | `"failed""` | 4 | ##### paymentConfirmation Enum Property *Property Definition* : An automatic property that is used to check the confirmed status of the payment set by webhooks.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **processing** | `"processing""` | 1 | | **paid** | `"paid""` | 2 | | **canceled** | `"canceled""` | 3 | ### Sys_subscriptionPayment resource *Resource Definition* : A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object's checkout config *Sys_subscriptionPayment Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **ownerId** | ID | | | * An ID value to represent owner user who created the order* | | **orderId** | ID | | | *an ID value to represent the orderId which is the ID parameter of the source subscription object* | | **paymentId** | String | | | *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 | | | *A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.* | | **statusLiteral** | String | | | *A string value to represent the logical payment status which belongs to the application lifecycle itself.* | | **redirectUrl** | String | | | *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.* | ### Sys_paymentCustomer resource *Resource Definition* : A payment storage object to store the customer values of the payment platform *Sys_paymentCustomer Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **userId** | ID | | | * An ID value to represent the user who is created as a stripe customer* | | **customerId** | String | | | *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 | | | *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.* | ### Sys_paymentMethod resource *Resource Definition* : A payment storage object to store the payment methods of the platform customers *Sys_paymentMethod Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **paymentMethodId** | String | | | *A string value to represent the id of the payment method on the payment platform.* | | **userId** | ID | | | * An ID value to represent the user who owns the payment method* | | **customerId** | String | | | *A string value to represent the customer id which is generated on the payment gateway.* | | **cardHolderName** | String | | | *A string value to represent the name of the card holder. It can be different than the registered customer.* | | **cardHolderZip** | String | | | *A string value to represent the zip code of the card holder. It is used for address verification in specific countries.* | | **platform** | String | | | *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 | | | *A Json value to store the card details of the payment method.* | ## Business Api ### `Cancel Subscription` API Cancel the authenticated user's active subscription. Sets the subscription status to cancelled and records the cancellation timestamp. **API Frontend Description By The Backend Architect** Call this endpoint when the user confirms they want to cancel their subscription. After successful cancellation, inform the user that they will lose access to AI features. The response contains the updated subscription record with status 'cancelled'. **Rest Route** The `cancelSubscription` API REST controller can be triggered via the following route: `/v1/subscriptions/:subscriptionId/cancel` **Rest Request Parameters** The `cancelSubscription` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/subscriptions/:subscriptionId/cancel** ```js axios({ method: 'POST', url: `/v1/subscriptions/${subscriptionId}/cancel`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Check Subscriptionstatus` API Machine-to-machine endpoint for other services to validate if a user has an active subscription. Returns the active subscription record if one exists, or an empty list if not. **Rest Route** The `checkSubscriptionStatus` API REST controller can be triggered via the following route: `/v1/check-status` **Rest Request Parameters** The `checkSubscriptionStatus` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.body?.["userId"] | **userId** : The user ID to check subscription status for. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/check-status** ```js axios({ method: 'POST', url: '/v1/check-status', data: { userId:"ID", }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscriptions", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "subscriptions": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Pricingconfig` API **[Default create API]** — This is the designated default `create` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new pricing configuration record. Admin-only operation for setting up subscription pricing. **Rest Route** The `createPricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs` **Rest Request Parameters** The `createPricingConfig` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | currency | String | true | request.body?.["currency"] | | description | Text | false | request.body?.["description"] | | price | Integer | true | request.body?.["price"] | | type | Enum | true | request.body?.["type"] | **currency** : Currency code for pricing (e.g., usd). **description** : Human-readable description of the subscription plan. **price** : Current subscription price in cents (e.g., 999 = $9.99). **type** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/pricingconfigs** ```js axios({ method: 'POST', url: '/v1/pricingconfigs', data: { currency:"String", description:"Text", price:"Integer", type:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Pricingconfig` API **[Default delete API]** — This is the designated default `delete` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a pricing configuration record. Admin-only operation. **Rest Route** The `deletePricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` **Rest Request Parameters** The `deletePricingConfig` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | **pricingConfigId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'DELETE', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Mysubscription` API Retrieve the currently authenticated user's active subscription. Returns the active subscription if one exists. **API Frontend Description By The Backend Architect** Use this endpoint to check if the current user has an active subscription before allowing access to AI features. If a 404 is returned, the user does not have an active subscription and should be prompted to subscribe. **Rest Route** The `getMySubscription` API REST controller can be triggered via the following route: `/v1/my-subscription` **Rest Request Parameters** The `getMySubscription` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/my-subscription** ```js axios({ method: 'GET', url: '/v1/my-subscription', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Pricingconfig` API **[Default get API]** — This is the designated default `get` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Retrieve a pricing configuration record. Accessible to all authenticated users to view current subscription pricing. **API Frontend Description By The Backend Architect** Use this endpoint to display the current subscription price to users before they initiate payment. **Rest Route** The `getPricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` **Rest Request Parameters** The `getPricingConfig` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | **pricingConfigId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'GET', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Subscription` API **[Default get API]** — This is the designated default `get` API for the `subscription` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Retrieve a subscription record by its ID. Owners can view their own subscriptions; admins can view any. **Rest Route** The `getSubscription` API REST controller can be triggered via the following route: `/v1/subscriptions/:subscriptionId` **Rest Request Parameters** The `getSubscription` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | **subscriptionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptions/:subscriptionId** ```js axios({ method: 'GET', url: `/v1/subscriptions/${subscriptionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Pricingconfigs` API **[Default list API]** — This is the designated default `list` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all pricing configuration records. Accessible to authenticated users. **Rest Route** The `listPricingConfigs` API REST controller can be triggered via the following route: `/v1/pricingconfigs` **Rest Request Parameters** The `listPricingConfigs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/pricingconfigs** ```js axios({ method: 'GET', url: '/v1/pricingconfigs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "pricingConfigs": [ { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Subscriptions` API **[Default list API]** — This is the designated default `list` API for the `subscription` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all subscriptions. Admin-only endpoint for monitoring subscription records. **Rest Route** The `listSubscriptions` API REST controller can be triggered via the following route: `/v1/subscriptions` **Rest Request Parameters** **Filter Parameters** The `listSubscriptions` api supports 3 optional filter parameters for filtering list results: **status** (`Enum`): Current subscription status managed by Stripe payment flow. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **userId** (`ID`): Reference to the user who owns this subscription. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptions** ```js axios({ method: 'GET', url: '/v1/subscriptions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // status: '' // Filter by status // userId: '' // Filter by userId // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscriptions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "subscriptions": [ { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Pricingconfig` API **[Default update API]** — This is the designated default `update` API for the `pricingConfig` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update the subscription pricing configuration. Admin-only operation for adjusting price, currency, or description without code deployment. **Rest Route** The `updatePricingConfig` API REST controller can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` **Rest Request Parameters** The `updatePricingConfig` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | | currency | String | false | request.body?.["currency"] | | description | Text | false | request.body?.["description"] | | price | Integer | false | request.body?.["price"] | | type | Enum | false | request.body?.["type"] | **pricingConfigId** : This id paremeter is used to select the required data object that will be updated **currency** : Currency code for pricing (e.g., usd). **description** : Human-readable description of the subscription plan. **price** : Current subscription price in cents (e.g., 999 = $9.99). **type** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'PATCH', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { currency:"String", description:"Text", price:"Integer", type:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Subscription` API **Rest Route** The `createSubscription` API REST controller can be triggered via the following route: `/v1/subscriptions` **Rest Request Parameters** The `createSubscription` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | activatedAt | Date | false | request.body?.["activatedAt"] | | cancelledAt | Date | false | request.body?.["cancelledAt"] | | currency | String | true | request.body?.["currency"] | | pricePaid | Integer | true | request.body?.["pricePaid"] | | statusUpdatedAt | Date | false | request.body?.["statusUpdatedAt"] | **activatedAt** : Timestamp when the subscription was activated after successful payment. **cancelledAt** : Timestamp when the subscription was cancelled by the user. **currency** : Currency code for the payment (e.g., usd). **pricePaid** : Amount paid in cents at the time of subscription activation. **statusUpdatedAt** : Timestamp of the last status update, auto-managed by Stripe payment flow. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/subscriptions** ```js axios({ method: 'POST', url: '/v1/subscriptions', data: { activatedAt:"Date", cancelledAt:"Date", currency:"String", pricePaid:"Integer", statusUpdatedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Do Test` API **Rest Route** The `test` API REST controller can be triggered via the following route: `/v1/test` **Rest Request Parameters** The `test` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/test** ```js axios({ method: 'GET', url: '/v1/test', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "pricingConfigs": [ { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Subscriptionpayment` API This route is used to get the payment information by ID. **Rest Route** The `getSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` **Rest Request Parameters** The `getSubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | **sys_subscriptionPaymentId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'GET', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Subscriptionpayments` API This route is used to list all payments. **Rest Route** The `listSubscriptionPayments` API REST controller can be triggered via the following route: `/v1/subscriptionpayments` **Rest Request Parameters** **Filter Parameters** The `listSubscriptionPayments` api supports 6 optional filter parameters for filtering list results: **ownerId** (`ID`): An ID value to represent owner user who created the order - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source subscription object - Single: `?orderId=` - Multiple: `?orderId=&orderId=` - Null: `?orderId=null` **paymentId** (`String`): 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 - Single (partial match, case-insensitive): `?paymentId=` - Multiple: `?paymentId=&paymentId=` - Null: `?paymentId=null` **paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. - Single (partial match, case-insensitive): `?paymentStatus=` - Multiple: `?paymentStatus=&paymentStatus=` - Null: `?paymentStatus=null` **statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself. - Single (partial match, case-insensitive): `?statusLiteral=` - Multiple: `?statusLiteral=&statusLiteral=` - Null: `?statusLiteral=null` **redirectUrl** (`String`): 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. - Single (partial match, case-insensitive): `?redirectUrl=` - Multiple: `?redirectUrl=&redirectUrl=` - Null: `?redirectUrl=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpayments** ```js axios({ method: 'GET', url: '/v1/subscriptionpayments', data: { }, params: { // Filter parameters (see Filter Parameters section above) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_subscriptionPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Subscriptionpayment` API This route is used to create a new payment. **Rest Route** The `createSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment` **Rest Request Parameters** The `createSubscriptionPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source subscription object **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/subscriptionpayment** ```js axios({ method: 'POST', url: '/v1/subscriptionpayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Subscriptionpayment` API This route is used to update an existing payment. **Rest Route** The `updateSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` **Rest Request Parameters** The `updateSubscriptionPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **sys_subscriptionPaymentId** : This id paremeter is used to select the required data object that will be updated **paymentId** : 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** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : 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. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'PATCH', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Subscriptionpayment` API This route is used to delete a payment. **Rest Route** The `deleteSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` **Rest Request Parameters** The `deleteSubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | **sys_subscriptionPaymentId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'DELETE', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Subscriptionpaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getSubscriptionPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/subscriptionpaymentbyorderid/:orderId` **Rest Request Parameters** The `getSubscriptionPaymentByOrderId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source subscription object. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/subscriptionpaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Subscriptionpaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getSubscriptionPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/subscriptionpaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getSubscriptionPaymentByPaymentId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | **paymentId** : 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. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/subscriptionpaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Start Subscriptionpayment` API Start payment for subscription **Rest Route** The `startSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/startsubscriptionpayment/:subscriptionId` **Rest Request Parameters** The `startSubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/startsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Refresh Subscriptionpayment` API Refresh payment info for subscription from Stripe **Rest Route** The `refreshSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/refreshsubscriptionpayment/:subscriptionId` **Rest Request Parameters** The `refreshSubscriptionPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **subscriptionId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to refresh a stripe payment process **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refreshsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/refreshsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Callback Subscriptionpayment` API Refresh payment values by gateway webhook call for subscription **Rest Route** The `callbackSubscriptionPayment` API REST controller can be triggered via the following route: `/v1/callbacksubscriptionpayment` **Rest Request Parameters** The `callbackSubscriptionPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | false | request.body?.["subscriptionId"] | **subscriptionId** : The order id parameter that will be read from webhook callback params **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/callbacksubscriptionpayment** ```js axios({ method: 'POST', url: '/v1/callbacksubscriptionpayment', data: { subscriptionId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Get Paymentcustomerbyuserid` API This route is used to get the payment customer information by user id. **Rest Route** The `getPaymentCustomerByUserId` API REST controller can be triggered via the following route: `/v1/paymentcustomers/:userId` **Rest Request Parameters** The `getPaymentCustomerByUserId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Paymentcustomers` API This route is used to list all payment customers. **Rest Route** The `listPaymentCustomers` API REST controller can be triggered via the following route: `/v1/paymentcustomers` **Rest Request Parameters** **Filter Parameters** The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results: **userId** (`ID`): An ID value to represent the user who is created as a stripe customer - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **customerId** (`String`): 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 - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Paymentcustomermethods` API This route is used to list all payment customer methods. **Rest Route** The `listPaymentCustomerMethods` API REST controller can be triggered via the following route: `/v1/paymentcustomermethods/:userId` **Rest Request Parameters** The `listPaymentCustomerMethods` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who owns the payment method. The parameter is used to query data. **Filter Parameters** The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results: **paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform. - Single (partial match, case-insensitive): `?paymentMethodId=` - Multiple: `?paymentMethodId=&paymentMethodId=` - Null: `?paymentMethodId=null` **customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway. - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer. - Single (partial match, case-insensitive): `?cardHolderName=` - Multiple: `?cardHolderName=&cardHolderName=` - Null: `?cardHolderName=null` **cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries. - Single (partial match, case-insensitive): `?cardHolderZip=` - Multiple: `?cardHolderZip=&cardHolderZip=` - Null: `?cardHolderZip=null` **platform** (`String`): 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. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **cardInfo** (`Object`): A Json value to store the card details of the payment method. - Single: `?cardInfo=` - Multiple: `?cardInfo=&cardInfo=` - Null: `?cardInfo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- ## EVENT GUIDE # EVENT GUIDE ## aifitapp-subscription-service Manages the single premium subscription plan lifecycle including activation, status tracking, cancellation, and admin-configurable pricing. Provides subscription status validation endpoints for other services to gate access to AI-powered featuresa.z ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. # Documentation Scope Welcome to the official documentation for the `Subscription` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `Subscription` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `Subscription` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `Subscription` objects. **Overview** This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples. # Authentication and Authorization Access to the `Subscription` service's events is facilitated through the project's Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server. Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide. # Database Events Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic. Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service's scope, ensuring data consistency and syncronization across services. For example, while a business operation such as "approve membership" might generate a high-level business event like `membership-approved`, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as `dbevent-member-updated` and `dbevent-user-updated`, reflecting the granular changes at the database level. Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes. ## DbEvent pricingConfig-created **Event topic**: `appaili-subscription-service-dbevent-pricingconfig-created` This event is triggered upon the creation of a `pricingConfig` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent pricingConfig-updated **Event topic**: `appaili-subscription-service-dbevent-pricingconfig-updated` Activation of this event follows the update of a `pricingConfig` data object. The payload contains the updated information under the `pricingConfig` attribute, along with the original data prior to update, labeled as `old_pricingConfig` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_pricingConfig:{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, pricingConfig:{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent pricingConfig-deleted **Event topic**: `appaili-subscription-service-dbevent-pricingconfig-deleted` This event announces the deletion of a `pricingConfig` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent subscription-created **Event topic**: `appaili-subscription-service-dbevent-subscription-created` This event is triggered upon the creation of a `subscription` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent subscription-updated **Event topic**: `appaili-subscription-service-dbevent-subscription-updated` Activation of this event follows the update of a `subscription` data object. The payload contains the updated information under the `subscription` attribute, along with the original data prior to update, labeled as `old_subscription` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_subscription:{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, subscription:{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent subscription-deleted **Event topic**: `appaili-subscription-service-dbevent-subscription-deleted` This event announces the deletion of a `subscription` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_subscriptionPayment-created **Event topic**: `appaili-subscription-service-dbevent-sys_subscriptionpayment-created` This event is triggered upon the creation of a `sys_subscriptionPayment` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_subscriptionPayment-updated **Event topic**: `appaili-subscription-service-dbevent-sys_subscriptionpayment-updated` Activation of this event follows the update of a `sys_subscriptionPayment` data object. The payload contains the updated information under the `sys_subscriptionPayment` attribute, along with the original data prior to update, labeled as `old_sys_subscriptionPayment` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_subscriptionPayment:{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_subscriptionPayment:{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_subscriptionPayment-deleted **Event topic**: `appaili-subscription-service-dbevent-sys_subscriptionpayment-deleted` This event announces the deletion of a `sys_subscriptionPayment` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentCustomer-created **Event topic**: `appaili-subscription-service-dbevent-sys_paymentcustomer-created` This event is triggered upon the creation of a `sys_paymentCustomer` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentCustomer-updated **Event topic**: `appaili-subscription-service-dbevent-sys_paymentcustomer-updated` Activation of this event follows the update of a `sys_paymentCustomer` data object. The payload contains the updated information under the `sys_paymentCustomer` attribute, along with the original data prior to update, labeled as `old_sys_paymentCustomer` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_paymentCustomer:{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_paymentCustomer:{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_paymentCustomer-deleted **Event topic**: `appaili-subscription-service-dbevent-sys_paymentcustomer-deleted` This event announces the deletion of a `sys_paymentCustomer` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentMethod-created **Event topic**: `appaili-subscription-service-dbevent-sys_paymentmethod-created` This event is triggered upon the creation of a `sys_paymentMethod` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_paymentMethod-updated **Event topic**: `appaili-subscription-service-dbevent-sys_paymentmethod-updated` Activation of this event follows the update of a `sys_paymentMethod` data object. The payload contains the updated information under the `sys_paymentMethod` attribute, along with the original data prior to update, labeled as `old_sys_paymentMethod` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_paymentMethod:{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_paymentMethod:{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_paymentMethod-deleted **Event topic**: `appaili-subscription-service-dbevent-sys_paymentmethod-deleted` This event announces the deletion of a `sys_paymentMethod` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` # ElasticSearch Index Events Within the `Subscription` service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects. These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries. It's noteworthy that some services may augment another service's index by appending to the entity’s `extends` object. In such scenarios, an `*-extended` event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID. This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications. ## Index Event pricingconfig-created **Event topic**: `elastic-index-aifitapp_pricingconfig-created` **Event payload**: ```json {"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event pricingconfig-updated **Event topic**: `elastic-index-aifitapp_pricingconfig-created` **Event payload**: ```json {"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event pricingconfig-deleted **Event topic**: `elastic-index-aifitapp_pricingconfig-deleted` **Event payload**: ```json {"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event pricingconfig-extended **Event topic**: `elastic-index-aifitapp_pricingconfig-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event subscription-canceled **Event topic** : `appaili-subscription-service-subscription-canceled` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-created **Event topic** : `appaili-subscription-service-pricingconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-deleted **Event topic** : `appaili-subscription-service-pricingconfig-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-updated **Event topic** : `appaili-subscription-service-pricingconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscription-created **Event topic** : `appaili-subscription-service-subscription-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"create","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event test-done **Event topic** : `appaili-subscription-service-test-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfigs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfigs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfigs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","pricingConfigs":[{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-retrived **Event topic** : `appaili-subscription-service-subscriptionpayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayments-listed **Event topic** : `appaili-subscription-service-subscriptionpayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_subscriptionPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-created **Event topic** : `appaili-subscription-service-subscriptionpayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-updated **Event topic** : `appaili-subscription-service-subscriptionpayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-deleted **Event topic** : `appaili-subscription-service-subscriptionpayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbyorderid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbypaymentid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-started **Event topic** : `appaili-subscription-service-subscriptionpayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-refreshed **Event topic** : `appaili-subscription-service-subscriptionpayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-calledback **Event topic** : `appaili-subscription-service-subscriptionpayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-subscription-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-subscription-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-subscription-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event subscription-created **Event topic**: `elastic-index-aifitapp_subscription-created` **Event payload**: ```json {"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event subscription-updated **Event topic**: `elastic-index-aifitapp_subscription-created` **Event payload**: ```json {"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event subscription-deleted **Event topic**: `elastic-index-aifitapp_subscription-deleted` **Event payload**: ```json {"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event subscription-extended **Event topic**: `elastic-index-aifitapp_subscription-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event subscription-canceled **Event topic** : `appaili-subscription-service-subscription-canceled` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-created **Event topic** : `appaili-subscription-service-pricingconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-deleted **Event topic** : `appaili-subscription-service-pricingconfig-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-updated **Event topic** : `appaili-subscription-service-pricingconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscription-created **Event topic** : `appaili-subscription-service-subscription-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"create","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event test-done **Event topic** : `appaili-subscription-service-test-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfigs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfigs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfigs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","pricingConfigs":[{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-retrived **Event topic** : `appaili-subscription-service-subscriptionpayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayments-listed **Event topic** : `appaili-subscription-service-subscriptionpayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_subscriptionPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-created **Event topic** : `appaili-subscription-service-subscriptionpayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-updated **Event topic** : `appaili-subscription-service-subscriptionpayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-deleted **Event topic** : `appaili-subscription-service-subscriptionpayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbyorderid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbypaymentid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-started **Event topic** : `appaili-subscription-service-subscriptionpayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-refreshed **Event topic** : `appaili-subscription-service-subscriptionpayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-calledback **Event topic** : `appaili-subscription-service-subscriptionpayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-subscription-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-subscription-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-subscription-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event sys_subscriptionpayment-created **Event topic**: `elastic-index-aifitapp_sys_subscriptionpayment-created` **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_subscriptionpayment-updated **Event topic**: `elastic-index-aifitapp_sys_subscriptionpayment-created` **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_subscriptionpayment-deleted **Event topic**: `elastic-index-aifitapp_sys_subscriptionpayment-deleted` **Event payload**: ```json {"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_subscriptionpayment-extended **Event topic**: `elastic-index-aifitapp_sys_subscriptionpayment-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event subscription-canceled **Event topic** : `appaili-subscription-service-subscription-canceled` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-created **Event topic** : `appaili-subscription-service-pricingconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-deleted **Event topic** : `appaili-subscription-service-pricingconfig-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-updated **Event topic** : `appaili-subscription-service-pricingconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscription-created **Event topic** : `appaili-subscription-service-subscription-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"create","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event test-done **Event topic** : `appaili-subscription-service-test-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfigs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfigs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfigs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","pricingConfigs":[{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-retrived **Event topic** : `appaili-subscription-service-subscriptionpayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayments-listed **Event topic** : `appaili-subscription-service-subscriptionpayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_subscriptionPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-created **Event topic** : `appaili-subscription-service-subscriptionpayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-updated **Event topic** : `appaili-subscription-service-subscriptionpayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-deleted **Event topic** : `appaili-subscription-service-subscriptionpayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbyorderid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbypaymentid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-started **Event topic** : `appaili-subscription-service-subscriptionpayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-refreshed **Event topic** : `appaili-subscription-service-subscriptionpayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-calledback **Event topic** : `appaili-subscription-service-subscriptionpayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-subscription-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-subscription-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-subscription-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event sys_paymentcustomer-created **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-created` **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentcustomer-updated **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-created` **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentcustomer-deleted **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-deleted` **Event payload**: ```json {"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentcustomer-extended **Event topic**: `elastic-index-aifitapp_sys_paymentcustomer-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event subscription-canceled **Event topic** : `appaili-subscription-service-subscription-canceled` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-created **Event topic** : `appaili-subscription-service-pricingconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-deleted **Event topic** : `appaili-subscription-service-pricingconfig-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-updated **Event topic** : `appaili-subscription-service-pricingconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscription-created **Event topic** : `appaili-subscription-service-subscription-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"create","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event test-done **Event topic** : `appaili-subscription-service-test-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfigs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfigs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfigs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","pricingConfigs":[{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-retrived **Event topic** : `appaili-subscription-service-subscriptionpayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayments-listed **Event topic** : `appaili-subscription-service-subscriptionpayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_subscriptionPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-created **Event topic** : `appaili-subscription-service-subscriptionpayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-updated **Event topic** : `appaili-subscription-service-subscriptionpayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-deleted **Event topic** : `appaili-subscription-service-subscriptionpayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbyorderid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbypaymentid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-started **Event topic** : `appaili-subscription-service-subscriptionpayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-refreshed **Event topic** : `appaili-subscription-service-subscriptionpayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-calledback **Event topic** : `appaili-subscription-service-subscriptionpayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-subscription-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-subscription-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-subscription-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event sys_paymentmethod-created **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-created` **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentmethod-updated **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-created` **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentmethod-deleted **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-deleted` **Event payload**: ```json {"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_paymentmethod-extended **Event topic**: `elastic-index-aifitapp_sys_paymentmethod-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event subscription-canceled **Event topic** : `appaili-subscription-service-subscription-canceled` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-created **Event topic** : `appaili-subscription-service-pricingconfig-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"POST","action":"create","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-deleted **Event topic** : `appaili-subscription-service-pricingconfig-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event pricingconfig-updated **Event topic** : `appaili-subscription-service-pricingconfig-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfig` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfig`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfig","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"pricingConfig":{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscription-created **Event topic** : `appaili-subscription-service-subscription-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"create","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event test-done **Event topic** : `appaili-subscription-service-test-done` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `pricingConfigs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`pricingConfigs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"pricingConfigs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","pricingConfigs":[{"id":"ID","currency":"String","description":"Text","price":"Integer","type":"Enum","type_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-retrived **Event topic** : `appaili-subscription-service-subscriptionpayment-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayments-listed **Event topic** : `appaili-subscription-service-subscriptionpayments-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_subscriptionPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event subscriptionpayment-created **Event topic** : `appaili-subscription-service-subscriptionpayment-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-updated **Event topic** : `appaili-subscription-service-subscriptionpayment-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-deleted **Event topic** : `appaili-subscription-service-subscriptionpayment-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbyorderid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbyorderid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpaymentbypaymentid-retrived **Event topic** : `appaili-subscription-service-subscriptionpaymentbypaymentid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_subscriptionPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_subscriptionPayment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_subscriptionPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_subscriptionPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event subscriptionpayment-started **Event topic** : `appaili-subscription-service-subscriptionpayment-started` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-refreshed **Event topic** : `appaili-subscription-service-subscriptionpayment-refreshed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event subscriptionpayment-calledback **Event topic** : `appaili-subscription-service-subscriptionpayment-calledback` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `subscription` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`subscription`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"subscription","method":"POST","action":"update","appVersion":"Version","rowCount":1,"subscription":{"id":"ID","activatedAt":"Date","cancelledAt":"Date","currency":"String","pricePaid":"Integer","status":"Enum","status_idx":"Integer","statusUpdatedAt":"Date","userId":"ID","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}} ``` ## Route Event paymentcustomerbyuserid-retrived **Event topic** : `appaili-subscription-service-paymentcustomerbyuserid-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomer` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomer`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event paymentcustomers-listed **Event topic** : `appaili-subscription-service-paymentcustomers-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentCustomers` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentCustomers`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event paymentcustomermethods-listed **Event topic** : `appaili-subscription-service-paymentcustomermethods-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_paymentMethods` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_paymentMethods`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` # Copyright All sources, documents and other digital materials are copyright of . # About Us For more information please visit our website: . . . --- ## Data Objects ### Service Design Specification - Object Design for pricingConfig # Service Design Specification - Object Design for pricingConfig **aifitapp-subscription-service** documentation ## Document Overview This document outlines the object design for the `pricingConfig` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## pricingConfig Data Object ### Object Overview **Description:** Stores the current premium subscription pricing configuration. Admin-managed, single system-wide record. 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. ### Redis Entity Caching This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster. ### Properties Schema **Display Label Property:** `description` — 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 | |----------|------|----------|-------------| | `currency` | String | Yes | Currency code for pricing (e.g., usd). | | `description` | Text | No | Human-readable description of the subscription plan. | | `price` | Integer | Yes | Current subscription price in cents (e.g., 999 = $9.99). | | `type` | 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. - **currency**: usd - **description**: Premium Subscription - AI Fitness & Nutrition Coach - **price**: 0 - **type**: subscription ### Auto Update Properties `currency` `description` `price` `type` 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. - **type**: [subscription, quota] ### Elastic Search Indexing `currency` `description` `price` `type` 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 `type` 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. --- ### Service Design Specification - Object Design for subscription # Service Design Specification - Object Design for subscription **aifitapp-subscription-service** documentation ## Document Overview This document outlines the object design for the `subscription` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## subscription Data Object ### Object Overview **Description:** Represents a user's premium subscription record, serving as the Stripe payment object. Tracks payment status, price paid, and subscription lifecycle dates. 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 `subscription`. 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**: `subscription` - **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**: 'Premium Subscription - AI Fitness & Nutrition Coach' 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 `'pending'` and will be set to `status`property. `paymentResultCanceled` status will be mapped to a local value using `'cancelled'` and will be set to `status` property. `paymentResultFailed` status will be mapped to a local value using `'failed'` and will be set to `status` property. `paymentResultSuccess` status will be mapped to a local value using `'active'` 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 | |----------|------|----------|-------------| | `activatedAt` | Date | No | Timestamp when the subscription was activated after successful payment. | | `cancelledAt` | Date | No | Timestamp when the subscription was cancelled by the user. | | `currency` | String | Yes | Currency code for the payment (e.g., usd). | | `pricePaid` | Integer | Yes | Amount paid in cents at the time of subscription activation. | | `status` | Enum | No | Current subscription status managed by Stripe payment flow. | | `statusUpdatedAt` | Date | No | Timestamp of the last status update, auto-managed by Stripe payment flow. | | `userId` | ID | Yes | Reference to the user who owns this subscription. | | `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. - **currency**: usd - **pricePaid**: 0 - **status**: pending - **userId**: '00000000-0000-0000-0000-000000000000' - **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. - **status**: Will be created with value `pending` - **paymentConfirmation**: Will be created with value `pending` ### Constant Properties `currency` `pricePaid` `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`. ### 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, active, cancelled, expired, failed] - **paymentConfirmation**: [pending, processing, paid, canceled] ### Elastic Search Indexing `activatedAt` `cancelledAt` `currency` `pricePaid` `status` `statusUpdatedAt` `userId` `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 `status` `userId` `paymentConfirmation` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Secondary Key Properties `paymentConfirmation` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Relation Properties `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` `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. - **status**: Enum has a filter named `status` - **userId**: ID has a filter named `userId` - **paymentConfirmation**: Enum has a filter named `paymentConfirmation` --- ### Service Design Specification - Object Design for sys_subscriptionPayment # Service Design Specification - Object Design for sys_subscriptionPayment **aifitapp-subscription-service** documentation ## Document Overview This document outlines the object design for the `sys_subscriptionPayment` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## sys_subscriptionPayment Data Object ### Object Overview **Description:** A payment storage object to store the payment life cyle of orders based on subscription object. It is autocreated based on the source object'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 subscription 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` --- ### Service Design Specification - Object Design for sys_paymentCustomer # Service Design Specification - Object Design for sys_paymentCustomer **aifitapp-subscription-service** documentation ## Document Overview This document outlines the object design for the `sys_paymentCustomer` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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` --- ### Service Design Specification - Object Design for sys_paymentMethod # Service Design Specification - Object Design for sys_paymentMethod **aifitapp-subscription-service** documentation ## Document Overview This document outlines the object design for the `sys_paymentMethod` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## 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 APIs ### Business API Design Specification - `Cancel Subscription` # Business API Design Specification - `Cancel Subscription` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `cancelSubscription` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `cancelSubscription` Business API is designed to handle a `update` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Cancel the authenticated user's active subscription. Sets the subscription status to cancelled and records the cancellation timestamp. ## API Frontend Description By The Backend Architect Call this endpoint when the user confirms they want to cancel their subscription. After successful cancellation, inform the user that they will lose access to AI features. The response contains the updated subscription record with status 'cancelled'. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscription-canceled` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `cancelSubscription` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptions/:subscriptionId/cancel` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `cancelSubscription` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `cancelSubscription` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `subscriptionId` | `ID` | `Yes` | `-` | `urlpath` | `subscriptionId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `cancelSubscription` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.subscriptionId},{isActive:true}]}), {"path":"services[2].businessLogic[0].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (2), {"path":"services[2].businessLogic[0].dataClause.customData[0].value"}), cancelledAt: runMScript(() => (new Date().toISOString()), {"path":"services[2].businessLogic[0].dataClause.customData[1].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // status parameter is closed to update by client request // include it in data clause unless you are sure status: runMScript(() => (2), {"path":"services[2].businessLogic[0].dataClause.customData[0].value"}), // cancelledAt parameter is closed to update by client request // include it in data clause unless you are sure cancelledAt: runMScript(() => (new Date().toISOString()), {"path":"services[2].businessLogic[0].dataClause.customData[1].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Action : validateActiveStatus **Action Type**: `ValidationAction` Ensure the subscription is currently active before allowing cancellation. ```js class Api { async validateActiveStatus() { const isValid = runMScript(() => this.subscription.status == 1, { path: "services[2].businessLogic[0].actions.validationActions[0].validationScript", }); if (!isValid) { throw new BadRequestError( "Subscription is not currently active and cannot be cancelled.", ); } return isValid; } } ``` --- ### [10] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [11] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [12] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [13] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [14] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `cancelSubscription` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/subscriptions/:subscriptionId/cancel** ```js axios({ method: 'POST', url: `/v1/subscriptions/${subscriptionId}/cancel`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Check Subscriptionstatus` # Business API Design Specification - `Check Subscriptionstatus` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `checkSubscriptionStatus` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `checkSubscriptionStatus` Business API is designed to handle a `list` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Machine-to-machine endpoint for other services to validate if a user has an active subscription. Returns the active subscription record if one exists, or an empty list if not. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `checkSubscriptionStatus` Business API includes a REST controller that can be triggered via the following route: `/v1/check-status` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `checkSubscriptionStatus` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `checkSubscriptionStatus` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `` | `body` | `userId` | | **Description:** | The user ID to check subscription status for. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `checkSubscriptionStatus` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API is **public** and can be accessed without login (`loginRequired = false`). --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `id`,`userId`,`status`,`activatedAt` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {userId: this.userId, status: "active"} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId: this.userId, status: "active"},{isActive:true}]}), {"path":"services[2].businessLogic[1].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `checkSubscriptionStatus` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.body?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/check-status** ```js axios({ method: 'POST', url: '/v1/check-status', data: { userId:"ID", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscriptions`** object in the respones. However, some properties may be omitted based on the object's internal logic. This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscriptions", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "subscriptions": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Pricingconfig` # Business API Design Specification - `Create Pricingconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createPricingConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createPricingConfig` Business API is designed to handle a `create` operation on the `PricingConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Create a new pricing configuration record. Admin-only operation for setting up subscription pricing. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `pricingconfig-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createPricingConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/pricingconfigs` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createPricingConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createPricingConfig` Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `pricingConfigId` | `ID` | `No` | `-` | `body` | `pricingConfigId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `currency` | `String` | `Yes` | `-` | `body` | `currency` | | **Description:** | Currency code for pricing (e.g., usd). | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Human-readable description of the subscription plan. | | | | | | | | | | | | | `price` | `Integer` | `Yes` | `-` | `body` | `price` | | **Description:** | Current subscription price in cents (e.g., 999 = $9.99). | | | | | | | | | | | | | `type` | `Enum` | `Yes` | `-` | `body` | `type` | | **Description:** | | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createPricingConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.pricingConfigId, currency: this.currency, description: this.description, price: this.price, type: this.type, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createPricingConfig` api has got 4 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | currency | String | true | request.body?.["currency"] | | description | Text | false | request.body?.["description"] | | price | Integer | true | request.body?.["price"] | | type | Enum | true | request.body?.["type"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/pricingconfigs** ```js axios({ method: 'POST', url: '/v1/pricingconfigs', data: { currency:"String", description:"Text", price:"Integer", type:"Enum", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`pricingConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Pricingconfig` # Business API Design Specification - `Delete Pricingconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deletePricingConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deletePricingConfig` Business API is designed to handle a `delete` operation on the `PricingConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Delete a pricing configuration record. Admin-only operation. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `pricingconfig-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deletePricingConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deletePricingConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deletePricingConfig` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `pricingConfigId` | `ID` | `Yes` | `-` | `urlpath` | `pricingConfigId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deletePricingConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.pricingConfigId},{isActive:true}]}), {"path":"services[2].businessLogic[3].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: true If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deletePricingConfig` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'DELETE', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`pricingConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Mysubscription` # Business API Design Specification - `Get Mysubscription` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getMySubscription` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getMySubscription` Business API is designed to handle a `get` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Retrieve the currently authenticated user's active subscription. Returns the active subscription if one exists. ## API Frontend Description By The Backend Architect Use this endpoint to check if the current user has an active subscription before allowing access to AI features. If a 404 is returned, the user does not have an active subscription and should be prompted to subscribe. ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getMySubscription` Business API includes a REST controller that can be triggered via the following route: `/v1/my-subscription` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getMySubscription` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getMySubscription` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getMySubscription` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has a `fullWhereClause` setting : ```js {userId: this.session.userId,status:"active"} ``` **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId: this.session.userId,status:"active"},{isActive:true}]}), {"path":"services[2].businessLogic[4].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getMySubscription` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/my-subscription** ```js axios({ method: 'GET', url: '/v1/my-subscription', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Pricingconfig` # Business API Design Specification - `Get Pricingconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getPricingConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getPricingConfig` Business API is designed to handle a `get` operation on the `PricingConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Retrieve a pricing configuration record. Accessible to all authenticated users to view current subscription pricing. ## API Frontend Description By The Backend Architect Use this endpoint to display the current subscription price to users before they initiate payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `true` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getPricingConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getPricingConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getPricingConfig` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `pricingConfigId` | `ID` | `Yes` | `-` | `urlpath` | `pricingConfigId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getPricingConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.pricingConfigId},{isActive:true}]}), {"path":"services[2].businessLogic[5].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getPricingConfig` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'GET', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`pricingConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Subscription` # Business API Design Specification - `Get Subscription` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getSubscription` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getSubscription` Business API is designed to handle a `get` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Retrieve a subscription record by its ID. Owners can view their own subscriptions; admins can view any. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getSubscription` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptions/:subscriptionId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getSubscription` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getSubscription` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `subscriptionId` | `ID` | `Yes` | `-` | `urlpath` | `subscriptionId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getSubscription` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[admin, superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.subscriptionId},{isActive:true}]}), {"path":"services[2].businessLogic[6].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getSubscription` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/subscriptions/:subscriptionId** ```js axios({ method: 'GET', url: `/v1/subscriptions/${subscriptionId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Pricingconfigs` # Business API Design Specification - `List Pricingconfigs` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listPricingConfigs` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listPricingConfigs` Business API is designed to handle a `list` operation on the `PricingConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List all pricing configuration records. Accessible to authenticated users. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listPricingConfigs` Business API includes a REST controller that can be triggered via the following route: `/v1/pricingconfigs` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listPricingConfigs` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPricingConfigs` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listPricingConfigs` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[2].businessLogic[7].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listPricingConfigs` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/pricingconfigs** ```js axios({ method: 'GET', url: '/v1/pricingconfigs', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`pricingConfigs`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "pricingConfigs": [ { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Subscriptions` # Business API Design Specification - `List Subscriptions` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listSubscriptions` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listSubscriptions` Business API is designed to handle a `list` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List all subscriptions. Admin-only endpoint for monitoring subscription records. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `false` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listSubscriptions` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptions` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listSubscriptions` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listSubscriptions` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listSubscriptions` api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `status` Filter **Type:** `Enum` **Description:** Current subscription status managed by Stripe payment flow. **Location:** Query Parameter **Usage:** - Single value: `?status=` (case-insensitive) - Multiple values: `?status=&status=` - Null check: `?status=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/subscriptions?status=active // Get records with multiple enum values (use multiple parameters) GET /v1/subscriptions?status=active&status=pending // Get records without this field GET /v1/subscriptions?status=null ``` #### `userId` Filter **Type:** `ID` **Description:** Reference to the user who owns this subscription. **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/subscriptions?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/subscriptions?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/subscriptions?userId=null ``` #### `paymentConfirmation` Filter **Type:** `Enum` **Description:** An automatic property that is used to check the confirmed status of the payment set by webhooks. **Location:** Query Parameter **Usage:** - Single value: `?paymentConfirmation=` (case-insensitive) - Multiple values: `?paymentConfirmation=&paymentConfirmation=` - Null check: `?paymentConfirmation=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/subscriptions?paymentConfirmation=active // Get records with multiple enum values (use multiple parameters) GET /v1/subscriptions?paymentConfirmation=active&paymentConfirmation=pending // Get records without this field GET /v1/subscriptions?paymentConfirmation=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listSubscriptions` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[2].businessLogic[8].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). [ createdAt desc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listSubscriptions` api has 3 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | status | Enum | No | Current subscription status managed by Stripe payment flow. | | userId | ID | No | Reference to the user who owns this subscription. | | paymentConfirmation | Enum | No | An automatic property that is used to check the confirmed status of the payment set by webhooks. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/subscriptions** ```js axios({ method: 'GET', url: '/v1/subscriptions', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // status: '' // Filter by status // userId: '' // Filter by userId // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscriptions`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscriptions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "subscriptions": [ { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Update Pricingconfig` # Business API Design Specification - `Update Pricingconfig` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updatePricingConfig` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updatePricingConfig` Business API is designed to handle a `update` operation on the `PricingConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Update the subscription pricing configuration. Admin-only operation for adjusting price, currency, or description without code deployment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `pricingconfig-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updatePricingConfig` Business API includes a REST controller that can be triggered via the following route: `/v1/pricingconfigs/:pricingConfigId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updatePricingConfig` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updatePricingConfig` Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `pricingConfigId` | `ID` | `Yes` | `-` | `urlpath` | `pricingConfigId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `currency` | `String` | `No` | `-` | `body` | `currency` | | **Description:** | Currency code for pricing (e.g., usd). | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Human-readable description of the subscription plan. | | | | | | | | | | | | | `price` | `Integer` | `No` | `-` | `body` | `price` | | **Description:** | Current subscription price in cents (e.g., 999 = $9.99). | | | | | | | | | | | | | `type` | `Enum` | `No` | `-` | `body` | `type` | | **Description:** | | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updatePricingConfig` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[admin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.pricingConfigId},{isActive:true}]}), {"path":"services[2].businessLogic[9].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { currency: this.currency, description: this.description, price: this.price, type: this.type, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updatePricingConfig` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | pricingConfigId | ID | true | request.params?.["pricingConfigId"] | | currency | String | false | request.body?.["currency"] | | description | Text | false | request.body?.["description"] | | price | Integer | false | request.body?.["price"] | | type | Enum | false | request.body?.["type"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/pricingconfigs/:pricingConfigId** ```js axios({ method: 'PATCH', url: `/v1/pricingconfigs/${pricingConfigId}`, data: { currency:"String", description:"Text", price:"Integer", type:"Enum", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`pricingConfig`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfig", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "pricingConfig": { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Create Subscription` # Business API Design Specification - `Create Subscription` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createSubscription` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createSubscription` Business API is designed to handle a `create` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscription-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createSubscription` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptions` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createSubscription` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createSubscription` Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `subscriptionId` | `ID` | `No` | `-` | `body` | `subscriptionId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `activatedAt` | `Date` | `No` | `-` | `body` | `activatedAt` | | **Description:** | Timestamp when the subscription was activated after successful payment. | | | | | | | | | | | | | `cancelledAt` | `Date` | `No` | `-` | `body` | `cancelledAt` | | **Description:** | Timestamp when the subscription was cancelled by the user. | | | | | | | | | | | | | `currency` | `String` | `Yes` | `-` | `body` | `currency` | | **Description:** | Currency code for the payment (e.g., usd). | | | | | | | | | | | | | `pricePaid` | `Integer` | `Yes` | `-` | `body` | `pricePaid` | | **Description:** | Amount paid in cents at the time of subscription activation. | | | | | | | | | | | | | `statusUpdatedAt` | `Date` | `No` | `-` | `body` | `statusUpdatedAt` | | **Description:** | Timestamp of the last status update, auto-managed by Stripe payment flow. | | | | | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `session` | `userId` | | **Description:** | Reference to the user who owns this subscription. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createSubscription` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.subscriptionId, activatedAt: this.activatedAt, cancelledAt: this.cancelledAt, currency: this.currency, pricePaid: this.pricePaid, statusUpdatedAt: this.statusUpdatedAt, userId: this.userId, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createSubscription` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | activatedAt | Date | false | request.body?.["activatedAt"] | | cancelledAt | Date | false | request.body?.["cancelledAt"] | | currency | String | true | request.body?.["currency"] | | pricePaid | Integer | true | request.body?.["pricePaid"] | | statusUpdatedAt | Date | false | request.body?.["statusUpdatedAt"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/subscriptions** ```js axios({ method: 'POST', url: '/v1/subscriptions', data: { activatedAt:"Date", cancelledAt:"Date", currency:"String", pricePaid:"Integer", statusUpdatedAt:"Date", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Do Test` # Business API Design Specification - `Do Test` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `test` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `test` Business API is designed to handle a `list` operation on the `PricingConfig` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `test-done` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `test` Business API includes a REST controller that can be triggered via the following route: `/v1/test` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `test` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `test` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `test` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` - **Check roles** (must pass basic role checks): Users must have at least one of the following roles to execute this API: `[superadmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[2].businessLogic[11].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `test` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/test** ```js axios({ method: 'GET', url: '/v1/test', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`pricingConfigs`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "pricingConfigs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "pricingConfigs": [ { "id": "ID", "currency": "String", "description": "Text", "price": "Integer", "type": "Enum", "type_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Get Subscriptionpayment` # Business API Design Specification - `Get Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getSubscriptionPayment` Business API is designed to handle a `get` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment information by ID. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getSubscriptionPayment` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_subscriptionPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_subscriptionPaymentId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.sys_subscriptionPaymentId},{isActive:true}]}), {"path":"services[2].businessLogic[12].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getSubscriptionPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'GET', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Subscriptionpayments` # Business API Design Specification - `List Subscriptionpayments` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listSubscriptionPayments` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listSubscriptionPayments` Business API is designed to handle a `list` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to list all payments. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayments-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listSubscriptionPayments` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpayments` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listSubscriptionPayments` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listSubscriptionPayments` Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listSubscriptionPayments` api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `ownerId` Filter **Type:** `ID` **Description:** An ID value to represent owner user who created the order **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?ownerId=` - Multiple values: `?ownerId=&ownerId=` - Null check: `?ownerId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/subscriptionpayments?ownerId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/subscriptionpayments?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/subscriptionpayments?ownerId=null ``` #### `orderId` Filter **Type:** `ID` **Description:** an ID value to represent the orderId which is the ID parameter of the source subscription object **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?orderId=` - Multiple values: `?orderId=&orderId=` - Null check: `?orderId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/subscriptionpayments?orderId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/subscriptionpayments?orderId=550e8400-e29b-41d4-a716-446655440000&orderId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/subscriptionpayments?orderId=null ``` #### `paymentId` Filter **Type:** `String` **Description:** 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 **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?paymentId=` (matches any string containing the value, case-insensitive) - Multiple values: `?paymentId=&paymentId=` (matches records containing any of the values) - Null check: `?paymentId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/subscriptionpayments?paymentId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/subscriptionpayments?paymentId=laptop&paymentId=phone&paymentId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/subscriptionpayments?paymentId=null ``` #### `paymentStatus` Filter **Type:** `String` **Description:** A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?paymentStatus=` (matches any string containing the value, case-insensitive) - Multiple values: `?paymentStatus=&paymentStatus=` (matches records containing any of the values) - Null check: `?paymentStatus=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/subscriptionpayments?paymentStatus=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/subscriptionpayments?paymentStatus=laptop&paymentStatus=phone&paymentStatus=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/subscriptionpayments?paymentStatus=null ``` #### `statusLiteral` Filter **Type:** `String` **Description:** A string value to represent the logical payment status which belongs to the application lifecycle itself. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?statusLiteral=` (matches any string containing the value, case-insensitive) - Multiple values: `?statusLiteral=&statusLiteral=` (matches records containing any of the values) - Null check: `?statusLiteral=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/subscriptionpayments?statusLiteral=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/subscriptionpayments?statusLiteral=laptop&statusLiteral=phone&statusLiteral=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/subscriptionpayments?statusLiteral=null ``` #### `redirectUrl` Filter **Type:** `String` **Description:** 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. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?redirectUrl=` (matches any string containing the value, case-insensitive) - Multiple values: `?redirectUrl=&redirectUrl=` (matches records containing any of the values) - Null check: `?redirectUrl=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/subscriptionpayments?redirectUrl=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/subscriptionpayments?redirectUrl=laptop&redirectUrl=phone&redirectUrl=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/subscriptionpayments?redirectUrl=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listSubscriptionPayments` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[2].businessLogic[13].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listSubscriptionPayments` api has 6 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | ownerId | ID | No | An ID value to represent owner user who created the order | | orderId | ID | No | an ID value to represent the orderId which is the ID parameter of the source subscription object | | paymentId | String | No | 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 | No | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | statusLiteral | String | No | 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. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpayments** ```js axios({ method: 'GET', url: '/v1/subscriptionpayments', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayments`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_subscriptionPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Subscriptionpayment` # Business API Design Specification - `Create Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createSubscriptionPayment` Business API is designed to handle a `create` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to create a new payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpayment` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createSubscriptionPayment` Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_subscriptionPaymentId` | `ID` | `No` | `-` | `body` | `sys_subscriptionPaymentId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `ownerId` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | An ID value to represent owner user who created the order | | | | | | | | | | | | | `orderId` | `ID` | `Yes` | `-` | `body` | `orderId` | | **Description:** | an ID value to represent the orderId which is the ID parameter of the source subscription object | | | | | | | | | | | | | `paymentId` | `String` | `Yes` | `-` | `body` | `paymentId` | | **Description:** | 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` | `-` | `body` | `paymentStatus` | | **Description:** | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | | | | | | | | | | | | `statusLiteral` | `String` | `Yes` | `-` | `body` | `statusLiteral` | | **Description:** | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | | | | | | | | | | | | `redirectUrl` | `String` | `No` | `-` | `body` | `redirectUrl` | | **Description:** | 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. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.sys_subscriptionPaymentId, ownerId: this.ownerId, orderId: this.orderId, paymentId: this.paymentId, paymentStatus: this.paymentStatus, statusLiteral: this.statusLiteral, redirectUrl: this.redirectUrl, isActive: true, _archivedAt: null, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createSubscriptionPayment` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/subscriptionpayment** ```js axios({ method: 'POST', url: '/v1/subscriptionpayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Subscriptionpayment` # Business API Design Specification - `Update Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateSubscriptionPayment` Business API is designed to handle a `update` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to update an existing payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateSubscriptionPayment` Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_subscriptionPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_subscriptionPaymentId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `ownerId` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | An ID value to represent owner user who created the order | | | | | | | | | | | | | `paymentId` | `String` | `No` | `-` | `body` | `paymentId` | | **Description:** | 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` | `No` | `-` | `body` | `paymentStatus` | | **Description:** | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | | | | | | | | | | | | `statusLiteral` | `String` | `No` | `-` | `body` | `statusLiteral` | | **Description:** | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | | | | | | | | | | | | `redirectUrl` | `String` | `No` | `-` | `body` | `redirectUrl` | | **Description:** | 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. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.sys_subscriptionPaymentId},{isActive:true}]}), {"path":"services[2].businessLogic[15].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { ownerId: this.ownerId, paymentId: this.paymentId, paymentStatus: this.paymentStatus, statusLiteral: this.statusLiteral, redirectUrl: this.redirectUrl, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateSubscriptionPayment` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'PATCH', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Subscriptionpayment` # Business API Design Specification - `Delete Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deleteSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deleteSubscriptionPayment` Business API is designed to handle a `delete` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to delete a payment. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deleteSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpayment/:sys_subscriptionPaymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deleteSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteSubscriptionPayment` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_subscriptionPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_subscriptionPaymentId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deleteSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.sys_subscriptionPaymentId},{isActive:true}]}), {"path":"services[2].businessLogic[16].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deleteSubscriptionPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_subscriptionPaymentId | ID | true | request.params?.["sys_subscriptionPaymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/subscriptionpayment/:sys_subscriptionPaymentId** ```js axios({ method: 'DELETE', url: `/v1/subscriptionpayment/${sys_subscriptionPaymentId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Subscriptionpaymentbyorderid` # Business API Design Specification - `Get Subscriptionpaymentbyorderid` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getSubscriptionPaymentByOrderId` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getSubscriptionPaymentByOrderId` Business API is designed to handle a `get` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment information by order id. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpaymentbyorderid-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getSubscriptionPaymentByOrderId` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpaymentbyorderid/:orderId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getSubscriptionPaymentByOrderId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getSubscriptionPaymentByOrderId` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `orderId` | `ID` | `Yes` | `-` | `urlpath` | `orderId` | | **Description:** | an ID value to represent the orderId which is the ID parameter of the source subscription object. The parameter is used to query data. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getSubscriptionPaymentByOrderId` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{orderId:{"$eq":this.orderId}},{isActive:true}]}), {"path":"services[2].businessLogic[17].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getSubscriptionPaymentByOrderId` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/subscriptionpaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Subscriptionpaymentbypaymentid` # Business API Design Specification - `Get Subscriptionpaymentbypaymentid` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getSubscriptionPaymentByPaymentId` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getSubscriptionPaymentByPaymentId` Business API is designed to handle a `get` operation on the `Sys_subscriptionPayment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment information by payment id. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpaymentbypaymentid-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getSubscriptionPaymentByPaymentId` Business API includes a REST controller that can be triggered via the following route: `/v1/subscriptionpaymentbypaymentid/:paymentId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getSubscriptionPaymentByPaymentId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getSubscriptionPaymentByPaymentId` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `paymentId` | `String` | `Yes` | `-` | `urlpath` | `paymentId` | | **Description:** | 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. The parameter is used to query data. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getSubscriptionPaymentByPaymentId` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{paymentId:{"$eq":this.paymentId}},{isActive:true}]}), {"path":"services[2].businessLogic[18].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getSubscriptionPaymentByPaymentId` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/subscriptionpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/subscriptionpaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_subscriptionPayment`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_subscriptionPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_subscriptionPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Start Subscriptionpayment` # Business API Design Specification - `Start Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `startSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `startSubscriptionPayment` Business API is designed to handle a `update` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Start payment for subscription ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-started` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `startSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/startsubscriptionpayment/:subscriptionId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `startSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `startSubscriptionPayment` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `subscriptionId` | `ID` | `Yes` | `-` | `urlpath` | `subscriptionId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `paymentUserParams` | `Object` | `Yes` | `-` | `body` | `paymentUserParams` | | **Description:** | The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `startSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.subscriptionId},{isActive:true}]}), {"path":"services[2].businessLogic[19].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[2].businessLogic[19].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[2].businessLogic[19].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[2].businessLogic[19].dataClause.customData[2].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // status parameter is closed to update by client request // include it in data clause unless you are sure status: runMScript(() => (this.status), {"path":"services[2].businessLogic[19].dataClause.customData[0].value"}), // statusUpdatedAt parameter is closed to update by client request // include it in data clause unless you are sure statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[2].businessLogic[19].dataClause.customData[1].value"}), // paymentConfirmation parameter is closed to update by client request // include it in data clause unless you are sure paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[2].businessLogic[19].dataClause.customData[2].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Action : checkPaymentMethodId **Action Type**: `ValidationAction` Validate that paymentMethodId is provided in paymentUserParams ```js class Api { async checkPaymentMethodId() { const isValid = runMScript( () => !!this.paymentUserParams?.paymentMethodId, { path: "services[2].businessLogic[19].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError( "paymentUserParams.paymentMethodId is required to start a payment", ); } return isValid; } } ``` --- ### [6] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [7] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [8] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [9] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [10] Action : doStartPayment **Action Type**: `PaymentAction` Start a payment on Stripe platform ```js class Api { getOrderId() { return this.subscriptionId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "appaili-subscription-service-subscriptionpaymentstatus-started"; case "updated": return "appaili-subscription-service-subscriptionpaymentstatus-updated"; case "succeeded": return "appaili-subscription-service-subscriptionpaymentstatus-succeeded"; case "failed": return "appaili-subscription-service-subscriptionpaymentstatus-failed"; case "paymentdone": return "appaili-subscription-service-subscription-paymentdone"; } } async paymentUpdated(statusLiteral) { switch (statusLiteral) { case "started": await this.paymentStarted(); break; case "canceled": await this.paymentCanceled(); break; case "failed": await this.paymentFailed(); break; case "success": await this.paymentDone(); break; default: await this.paymentFailed(); break; } } async paymentStarted() { this.status = runMScript(() => "pending", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.status = runMScript(() => "cancelled", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.status = runMScript(() => "failed", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.status = runMScript(() => "active", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript( () => "Premium Subscription - AI Fitness & Nutrition Coach", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.description", }, ); const metadata = { order: "Subscription-Subscription-order", orderId: this.subscription.id, paymentName: "subscription", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.subscription.pricePaid, currency: this.subscription.currency, orderId: this.subscription.id, metadata: metadata, storeCard: userParams?.storeCard, paymentUserParams: userParams, bodyParams: this.bodyParams, }; } async doStartPayment() { // Handle Payment Action try { if (!this.paymentManager) { throw new Error( "This dboject is not an order object. So auto-payment process can not be started.", ); } this.paymentResult = await this.paymentManager.startPayment( this.paymentUserParams, ); } catch (err) { if (err instanceof PaymentGateError) { this.paymentResult = err.serializeError(); //**errorLog } else throw err; } return this.paymentResult; } } ``` --- ### [11] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [12] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [13] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [14] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [15] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `startSubscriptionPayment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/startsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/startsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` --- ### Business API Design Specification - `Refresh Subscriptionpayment` # Business API Design Specification - `Refresh Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `refreshSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `refreshSubscriptionPayment` Business API is designed to handle a `update` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Refresh payment info for subscription from Stripe ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-refreshed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `refreshSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/refreshsubscriptionpayment/:subscriptionId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `refreshSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `refreshSubscriptionPayment` Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `subscriptionId` | `ID` | `Yes` | `-` | `urlpath` | `subscriptionId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `paymentUserParams` | `Object` | `No` | `-` | `body` | `paymentUserParams` | | **Description:** | The user parameters that should be defined to refresh a stripe payment process | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `refreshSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks This Business API enforces ownership of the main data object before executing the operation. - The check is performed **after fetching the object instance**. If the current user is not the owner, the API will respond with **403 Forbidden**. Note: Ownership checks are applied **only if the objects have an owner field**. --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.subscriptionId},{isActive:true}]}), {"path":"services[2].businessLogic[20].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[2].businessLogic[20].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[2].businessLogic[20].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[2].businessLogic[20].dataClause.customData[2].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // status parameter is closed to update by client request // include it in data clause unless you are sure status: runMScript(() => (this.status), {"path":"services[2].businessLogic[20].dataClause.customData[0].value"}), // statusUpdatedAt parameter is closed to update by client request // include it in data clause unless you are sure statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[2].businessLogic[20].dataClause.customData[1].value"}), // paymentConfirmation parameter is closed to update by client request // include it in data clause unless you are sure paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[2].businessLogic[20].dataClause.customData[2].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Action : doRefreshPayment **Action Type**: `PaymentAction` Refresh payment from Stripe platform, the payment operation data in the gateway server will be fetched and the application payment tickets and order status will be refreshed according to the server. This api may be used if you dont want to use a webhook. ```js class Api { getOrderId() { return this.subscriptionId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "appaili-subscription-service-subscriptionpaymentstatus-started"; case "updated": return "appaili-subscription-service-subscriptionpaymentstatus-updated"; case "succeeded": return "appaili-subscription-service-subscriptionpaymentstatus-succeeded"; case "failed": return "appaili-subscription-service-subscriptionpaymentstatus-failed"; case "paymentdone": return "appaili-subscription-service-subscription-paymentdone"; } } async paymentUpdated(statusLiteral) { switch (statusLiteral) { case "started": await this.paymentStarted(); break; case "canceled": await this.paymentCanceled(); break; case "failed": await this.paymentFailed(); break; case "success": await this.paymentDone(); break; default: await this.paymentFailed(); break; } } async paymentStarted() { this.status = runMScript(() => "pending", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.status = runMScript(() => "cancelled", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.status = runMScript(() => "failed", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.status = runMScript(() => "active", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript( () => "Premium Subscription - AI Fitness & Nutrition Coach", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.description", }, ); const metadata = { order: "Subscription-Subscription-order", orderId: this.subscription.id, paymentName: "subscription", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.subscription.pricePaid, currency: this.subscription.currency, orderId: this.subscription.id, metadata: metadata, storeCard: userParams?.storeCard, paymentUserParams: userParams, bodyParams: this.bodyParams, }; } async doRefreshPayment() { // Handle Payment Action try { if (!this.paymentManager) { throw new Error( "This dboject is not an order object. So auto-payment process can not be started.", ); } this.paymentResult = await this.paymentManager.refreshPayment( this.paymentUserParams, ); } catch (err) { if (err instanceof PaymentGateError) { this.paymentResult = err.serializeError(); //**errorLog } else throw err; } return this.paymentResult; } } ``` --- ### [10] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [11] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [12] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [13] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [14] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `refreshSubscriptionPayment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | true | request.params?.["subscriptionId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/refreshsubscriptionpayment/:subscriptionId** ```js axios({ method: 'PATCH', url: `/v1/refreshsubscriptionpayment/${subscriptionId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` --- ### Business API Design Specification - `Callback Subscriptionpayment` # Business API Design Specification - `Callback Subscriptionpayment` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `callbackSubscriptionPayment` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `callbackSubscriptionPayment` Business API is designed to handle a `update` operation on the `Subscription` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Refresh payment values by gateway webhook call for subscription ## API Options * **Auto Params** : `false` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `subscriptionpayment-calledback` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `callbackSubscriptionPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/callbacksubscriptionpayment` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `callbackSubscriptionPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `callbackSubscriptionPayment` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `subscriptionId` | `ID` | `No` | `-` | `body` | `subscriptionId` | | **Description:** | The order id parameter that will be read from webhook callback params | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. * `subscriptionId`: ```javascript this.subscriptionId = runMScript(() => (this.paymentCallbackParams?.orderId), {"path":"services[2].businessLogic[21].customParameters[0].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `callbackSubscriptionPayment` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API is **public** and can be accessed without login (`loginRequired = false`). --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{id:this.subscriptionId},{isActive:true}]}), {"path":"services[2].businessLogic[21].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** ```js { status: runMScript(() => (this.status), {"path":"services[2].businessLogic[21].dataClause.customData[0].value"}), statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[2].businessLogic[21].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[2].businessLogic[21].dataClause.customData[2].value"}), } ``` **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { // status parameter is closed to update by client request // include it in data clause unless you are sure status: runMScript(() => (this.status), {"path":"services[2].businessLogic[21].dataClause.customData[0].value"}), // statusUpdatedAt parameter is closed to update by client request // include it in data clause unless you are sure statusUpdatedAt: runMScript(() => (new Date()), {"path":"services[2].businessLogic[21].dataClause.customData[1].value"}), // paymentConfirmation parameter is closed to update by client request // include it in data clause unless you are sure paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[2].businessLogic[21].dataClause.customData[2].value"}), } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Action : verifyPaymentWebhook **Action Type**: `VerifyWebhookAction` Verify a providers webhook call with the secret signature and read the params, write the callback parameters to the context. Only stripe webhooks is supported for now. ```js class Api { // Code for VerifyWebhookAction async verifyPaymentWebhook() { const secretKey = runMScript(() => process.env.STRIPE_WEBHOOK_SECRET, { path: "services[2].businessLogic[21].actions.verifyWebhookActions[0].secretKey", }); await this.paymentManager.ensurePaymentGate(); const stripeGateway = this.paymentManager.paymentGate; const result = await stripeGateway.webhookController(this.request); console.log("VerifyWebhookAction result -->", result); if (result.statusLiteral == "unhandled") { throw new BadRequestError( `Unhandled stripe webhook event [${result.eventType}]`, ); } return result; } } ``` --- ### [4] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [5] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [6] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [7] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [8] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [9] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [10] Action : doPaymentCallback **Action Type**: `PaymentAction` Refresh payment by Stripe platform webhook, the payment operation data in the gateway server will be given by webhook call and the application payment tickets and order status will be refreshed according to the server. ```js class Api { getOrderId() { return this.subscriptionId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "appaili-subscription-service-subscriptionpaymentstatus-started"; case "updated": return "appaili-subscription-service-subscriptionpaymentstatus-updated"; case "succeeded": return "appaili-subscription-service-subscriptionpaymentstatus-succeeded"; case "failed": return "appaili-subscription-service-subscriptionpaymentstatus-failed"; case "paymentdone": return "appaili-subscription-service-subscription-paymentdone"; } } async paymentUpdated(statusLiteral) { switch (statusLiteral) { case "started": await this.paymentStarted(); break; case "canceled": await this.paymentCanceled(); break; case "failed": await this.paymentFailed(); break; case "success": await this.paymentDone(); break; default: await this.paymentFailed(); break; } } async paymentStarted() { this.status = runMScript(() => "pending", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.status = runMScript(() => "cancelled", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.status = runMScript(() => "failed", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.status = runMScript(() => "active", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript( () => "Premium Subscription - AI Fitness & Nutrition Coach", { path: "services[2].dataObjects[1].objectSettings.stripeOrder.configuration.description", }, ); const metadata = { order: "Subscription-Subscription-order", orderId: this.subscription.id, paymentName: "subscription", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.subscription.pricePaid, currency: this.subscription.currency, orderId: this.subscription.id, metadata: metadata, storeCard: userParams?.storeCard, paymentUserParams: userParams, bodyParams: this.bodyParams, }; } async doPaymentCallback() { // Handle Payment Action try { if (!this.paymentManager) { throw new Error( "This dboject is not an order object. So auto-payment process can not be started.", ); } this.paymentResult = await this.paymentManager.processPaymentCallbackResult( this.paymentCallbackParams, ); } catch (err) { if (err instanceof PaymentGateError) { this.paymentResult = err.serializeError(); //**errorLog } else throw err; } return this.paymentResult; } } ``` --- ### [11] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [12] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [13] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [14] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [15] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `callbackSubscriptionPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | subscriptionId | ID | false | request.body?.["subscriptionId"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/callbacksubscriptionpayment** ```js axios({ method: 'POST', url: '/v1/callbacksubscriptionpayment', data: { subscriptionId:"ID", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`subscription`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "subscription", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "subscription": { "id": "ID", "activatedAt": "Date", "cancelledAt": "Date", "currency": "String", "pricePaid": "Integer", "status": "Enum", "status_idx": "Integer", "statusUpdatedAt": "Date", "userId": "ID", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` --- ### Business API Design Specification - `Get Paymentcustomerbyuserid` # Business API Design Specification - `Get Paymentcustomerbyuserid` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getPaymentCustomerByUserId` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getPaymentCustomerByUserId` Business API is designed to handle a `get` operation on the `Sys_paymentCustomer` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to get the payment customer information by user id. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `paymentcustomerbyuserid-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getPaymentCustomerByUserId` Business API includes a REST controller that can be triggered via the following route: `/v1/paymentcustomers/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getPaymentCustomerByUserId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getPaymentCustomerByUserId` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getPaymentCustomerByUserId` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId:{"$eq":this.userId}},{isActive:true}]}), {"path":"services[2].businessLogic[22].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getPaymentCustomerByUserId` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_paymentCustomer`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Paymentcustomers` # Business API Design Specification - `List Paymentcustomers` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listPaymentCustomers` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listPaymentCustomers` Business API is designed to handle a `list` operation on the `Sys_paymentCustomer` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to list all payment customers. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `paymentcustomers-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listPaymentCustomers` Business API includes a REST controller that can be triggered via the following route: `/v1/paymentcustomers` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listPaymentCustomers` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPaymentCustomers` Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `userId` Filter **Type:** `ID` **Description:** An ID value to represent the user who is created as a stripe customer **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/paymentcustomers?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/paymentcustomers?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/paymentcustomers?userId=null ``` #### `customerId` Filter **Type:** `String` **Description:** 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 **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?customerId=` (matches any string containing the value, case-insensitive) - Multiple values: `?customerId=&customerId=` (matches records containing any of the values) - Null check: `?customerId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomers?customerId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomers?customerId=laptop&customerId=phone&customerId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomers?customerId=null ``` #### `platform` Filter **Type:** `String` **Description:** 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. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?platform=` (matches any string containing the value, case-insensitive) - Multiple values: `?platform=&platform=` (matches records containing any of the values) - Null check: `?platform=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomers?platform=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomers?platform=laptop&platform=phone&platform=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomers?platform=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listPaymentCustomers` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({isActive:true}), {"path":"services[2].businessLogic[23].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listPaymentCustomers` api has 3 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | userId | ID | No | An ID value to represent the user who is created as a stripe customer | | customerId | String | No | 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 | No | 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. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_paymentCustomers`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Paymentcustomermethods` # Business API Design Specification - `List Paymentcustomermethods` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listPaymentCustomerMethods` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listPaymentCustomerMethods` Business API is designed to handle a `list` operation on the `Sys_paymentMethod` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description This route is used to list all payment customer methods. ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `paymentcustomermethods-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `false` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listPaymentCustomerMethods` Business API includes a REST controller that can be triggered via the following route: `/v1/paymentcustomermethods/:userId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listPaymentCustomerMethods` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPaymentCustomerMethods` Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `userId` | `ID` | `Yes` | `-` | `urlpath` | `userId` | | **Description:** | An ID value to represent the user who owns the payment method. The parameter is used to query data. | | | | | | | | | | | | ### Filter Parameters The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `paymentMethodId` Filter **Type:** `String` **Description:** A string value to represent the id of the payment method on the payment platform. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?paymentMethodId=` (matches any string containing the value, case-insensitive) - Multiple values: `?paymentMethodId=&paymentMethodId=` (matches records containing any of the values) - Null check: `?paymentMethodId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?paymentMethodId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?paymentMethodId=laptop&paymentMethodId=phone&paymentMethodId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?paymentMethodId=null ``` #### `customerId` Filter **Type:** `String` **Description:** A string value to represent the customer id which is generated on the payment gateway. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?customerId=` (matches any string containing the value, case-insensitive) - Multiple values: `?customerId=&customerId=` (matches records containing any of the values) - Null check: `?customerId=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?customerId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?customerId=laptop&customerId=phone&customerId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?customerId=null ``` #### `cardHolderName` Filter **Type:** `String` **Description:** A string value to represent the name of the card holder. It can be different than the registered customer. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?cardHolderName=` (matches any string containing the value, case-insensitive) - Multiple values: `?cardHolderName=&cardHolderName=` (matches records containing any of the values) - Null check: `?cardHolderName=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?cardHolderName=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?cardHolderName=laptop&cardHolderName=phone&cardHolderName=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?cardHolderName=null ``` #### `cardHolderZip` Filter **Type:** `String` **Description:** A string value to represent the zip code of the card holder. It is used for address verification in specific countries. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?cardHolderZip=` (matches any string containing the value, case-insensitive) - Multiple values: `?cardHolderZip=&cardHolderZip=` (matches records containing any of the values) - Null check: `?cardHolderZip=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?cardHolderZip=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?cardHolderZip=laptop&cardHolderZip=phone&cardHolderZip=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?cardHolderZip=null ``` #### `platform` Filter **Type:** `String` **Description:** 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. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?platform=` (matches any string containing the value, case-insensitive) - Multiple values: `?platform=&platform=` (matches records containing any of the values) - Null check: `?platform=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/paymentcustomermethods/:userId?platform=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?platform=laptop&platform=phone&platform=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/paymentcustomermethods/:userId?platform=null ``` #### `cardInfo` Filter **Type:** `Object` **Description:** A Json value to store the card details of the payment method. **Location:** Query Parameter **Usage:** - Single value: `?cardInfo=` - Multiple values: `?cardInfo=&cardInfo=` - Null check: `?cardInfo=null` **Examples:** ```javascript // Get records with specific value GET /v1/paymentcustomermethods/:userId?cardInfo= // Get records with multiple values (use multiple parameters) GET /v1/paymentcustomermethods/:userId?cardInfo=&cardInfo= // Get records without this field GET /v1/paymentcustomermethods/:userId?cardInfo=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listPaymentCustomerMethods` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. The business api configuration has a `selectBy` setting: '['']` **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{userId:{"$eq":this.userId}},{isActive:true}]}), {"path":"services[2].businessLogic[24].whereClause.fullWhereClause"}) ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listPaymentCustomerMethods` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | The `listPaymentCustomerMethods` api has 6 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | paymentMethodId | String | No | A string value to represent the id of the payment method on the payment platform. | | customerId | String | No | 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 | No | 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 | No | A Json value to store the card details of the payment method. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_paymentMethods`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ## Service Library - `subscription` # Service Library - `subscription` This document provides a complete reference of the custom code library for the `subscription` service. It includes all library functions, edge functions with their REST endpoints, templates, and assets. ## Edge Functions Edge functions are custom HTTP endpoint handlers that run outside the standard Business API pipeline. Each edge function is paired with an Edge Controller that defines its REST endpoint. ### `onPaymentDone.js` **Edge Controller:** - **Path:** `` - **Method:** `GET` - **Login Required:** No ```js const { updateSubscriptionById } = require("dbLayer"); module.exports = async (request) => { const subscription = request.subscription; if (subscription && subscription.id) { await updateSubscriptionById(subscription.id, { activatedAt: new Date().toISOString() }); } return { status: 200, message: "Subscription activated successfully" }; }; ``` ### `onPricingConfigCreated.js` **Edge Controller:** - **Path:** `/pricing-config-created` - **Method:** `GET` - **Login Required:** No ```js const { fetchRemoteListByMQuery } = require("serviceCommon"); const axios = require("axios"); // HTML Email Template const getEmailHtml = (data) => { return `

Exciting News, ${data.userFullname}!

We're thrilled to announce a new premium plan option for AI Fitness & Nutrition Coach!

New Plan Details:

  • Price: ${(data.pricingAmount / 100).toFixed(2)} ${data.pricingCurrency.toUpperCase()}
  • Description: ${data.pricingDescription || 'Premium Subscription'}

With this premium subscription, you'll unlock:

  • Personalized Training Programs — Evidence-based workout routines tailored to your goals
  • Custom Nutrition Plans — Calorie and macro targets with regional meal suggestions
  • AI Fitness Coach Chatbot — Get real-time guidance, exercise substitutions, and food alternatives
  • Dynamic Program Adjustments — Your plans evolve as you progress
  • Weight Tracking & Optimization — Report your weight and let AI optimize your plan

Ready to take your fitness journey to the next level? Log in to your account and upgrade today!

Best regards,
The AI Fitness Coach Team

`; }; module.exports = async (request) => { try { // Get pricing config data from the Kafka event const pricingConfig = request.pricingConfig; if (!pricingConfig) { console.log("No pricing config data in event"); return { status: 200, message: "No pricing config data" }; } console.log(`New pricing config created: ${pricingConfig.id}`); // Fetch all users from auth service via Elasticsearch // Using empty query to get all users, with high limit const users = await fetchRemoteListByMQuery( "User", {}, // Empty query = all users 0, // from 1000, // size - adjust based on your user count [{ createdAt: { order: "desc" } }] ); console.log(`Found ${users.length} users to notify`); if (!users || users.length === 0) { return { status: 200, message: "No users found to notify" }; } // Get notification service URL from environment const notificationServiceUrl = process.env.NOTIFICATION_SERVICE_URL || "http://notification-service:3000"; // Send email to each user const emailPromises = users.map(async (user) => { try { const emailHtml = getEmailHtml({ userFullname: user.fullname, pricingAmount: pricingConfig.amount, pricingCurrency: pricingConfig.currency, pricingDescription: pricingConfig.description }); const notificationPayload = { types: ["email"], template: "NONE", // Use direct body instead of template to: user.email, isStored: false, title: "New Premium Plan Available!", body: emailHtml, metadata: { userFullname: user.fullname, pricingAmount: pricingConfig.amount, pricingCurrency: pricingConfig.currency, configId: pricingConfig.id } }; await axios.post( `${notificationServiceUrl}/notifications`, notificationPayload ); console.log(`Email sent to ${user.email}`); return { success: true, email: user.email }; } catch (error) { console.error(`Failed to send email to ${user.email}:`, error.message); return { success: false, email: user.email, error: error.message }; } }); const results = await Promise.allSettled(emailPromises); const successCount = results.filter(r => r.status === 'fulfilled' && r.value.success).length; const failCount = results.length - successCount; console.log(`Email broadcast complete: ${successCount} successful, ${failCount} failed`); return { status: 200, message: `Pricing config notification sent to ${successCount} users (${failCount} failed)`, totalUsers: users.length, successCount, failCount }; } catch (error) { console.error("Error in onPricingConfigCreated:", error); return { status: 500, message: "Error processing pricing config notification", error: error.message }; } }; ``` ## Edge Controllers Summary | Function Name | Method | Path | Login Required | |--------------|--------|------|----------------| | `onPricingConfigCreated` | `GET` | `/pricing-config-created` | No | | `onPaymentDone` | `GET` | `` | No | --- *This document was generated from the service library configuration and should be kept in sync with design changes.* --- # AgentHub Service ## Service Design Specification # Service Design Specification **aifitapp-agenthub-service** documentation **Version:** `1.0.0` ## Scope This document provides a structured architectural overview of the `agentHub` 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. ## `AgentHub` Service Settings AI Agent Hub ### Service Overview This service is configured to listen for HTTP requests on port `3006`, 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-agenthub-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://appaili.prw.mindbricks.com/agenthub-api` * **Staging:** `https://appaili-stage.mindbricks.co/agenthub-api` * **Production:** `https://appaili.mindbricks.co/agenthub-api` ### Authentication & Security - **Login Required**: Yes This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `aifitapp-agenthub-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 | |-------------|-------------|---------------| | `sys_agentOverride` | Runtime overrides for design-time agents. Null fields use the design default. | accessProtected | | `sys_agentExecution` | Agent execution log. Records each agent invocation with input, output, and performance metrics. | accessProtected | | `sys_toolCatalog` | Cached tool catalog discovered from project services. Refreshed periodically. | accessProtected | ## sys_agentOverride Data Object ### Object Overview **Description:** Runtime overrides for design-time agents. Null fields use the design default. 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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `agentName` | String | Yes | Design-time agent name this override applies to. | | `provider` | String | No | Override AI provider (e.g., openai, anthropic). | | `model` | String | No | Override model name. | | `systemPrompt` | Text | No | Override system prompt. | | `temperature` | Double | No | Override temperature (0-2). | | `maxTokens` | Integer | No | Override max tokens. | | `responseFormat` | String | No | Override response format (text/json). | | `selectedTools` | Object | No | Array of tool names from the catalog that this agent can use. | | `guardrails` | Object | No | Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. | | `enabled` | Boolean | Yes | Enable or disable this agent. | | `updatedBy` | ID | No | User who last updated this override. | * 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. - **agentName**: 'default' - **enabled**: true ### 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. - **enabled**: Will be created with value `true` ### Constant Properties `agentName` 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 `agentName` `provider` `model` `systemPrompt` `temperature` `maxTokens` `responseFormat` `selectedTools` `guardrails` `enabled` `updatedBy` 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 `agentName` `enabled` 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 `agentName` `enabled` 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 `agentName` 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. ### Session Data Properties `updatedBy` 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. - **updatedBy**: ID property will be mapped to the session parameter `userId`. ## sys_agentExecution Data Object ### Object Overview **Description:** Agent execution log. Records each agent invocation with input, output, and performance metrics. 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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `agentName` | String | Yes | Agent that was executed. | | `agentType` | Enum | Yes | Whether this was a design-time or dynamic agent. | | `source` | Enum | Yes | How the agent was triggered. | | `userId` | ID | No | User who triggered the execution. | | `input` | Object | No | Request input (truncated for large payloads). | | `output` | Object | No | Response output (truncated for large payloads). | | `toolCalls` | Integer | No | Number of tool calls made during execution. | | `tokenUsage` | Object | No | Token usage: { prompt, completion, total }. | | `durationMs` | Integer | No | Execution time in milliseconds. | | `status` | Enum | Yes | Execution status. | | `error` | Text | No | Error message if execution failed. | * 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. - **agentName**: 'default' - **agentType**: "design" - **source**: "rest" - **status**: "success" ### Constant Properties `agentName` `agentType` `source` `userId` `input` `output` `toolCalls` `tokenUsage` `durationMs` `status` `error` 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 `agentName` `agentType` `source` `userId` `input` `output` `toolCalls` `tokenUsage` `durationMs` `status` `error` 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. - **agentType**: [design, dynamic] - **source**: [rest, sse, kafka, agent] - **status**: [success, error, timeout] ### Elastic Search Indexing `agentName` `agentType` `source` `userId` `toolCalls` `durationMs` `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 `agentName` `agentType` `source` `userId` `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. ### Filter Properties `agentName` `agentType` `source` `userId` `status` 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. - **agentName**: String has a filter named `agentName` - **agentType**: Enum has a filter named `agentType` - **source**: Enum has a filter named `source` - **userId**: ID has a filter named `userId` - **status**: Enum has a filter named `status` ## sys_toolCatalog Data Object ### Object Overview **Description:** Cached tool catalog discovered from project services. Refreshed periodically. 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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `toolName` | String | Yes | Full tool name (e.g., service:apiName). | | `serviceName` | String | Yes | Source service name. | | `description` | Text | No | Tool description. | | `parameters` | Object | No | JSON Schema of tool parameters. | | `lastRefreshed` | Date | No | When this tool was last discovered/refreshed. | * 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. - **toolName**: 'default' - **serviceName**: 'default' ### Auto Update Properties `toolName` `serviceName` `description` `parameters` `lastRefreshed` 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 `toolName` `serviceName` `description` 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 `toolName` `serviceName` 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 `toolName` 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. ### Filter Properties `serviceName` 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. - **serviceName**: String has a filter named `serviceName` ## Business Logic agentHub has got 9 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Get Agentoverride](/document/businessLogic/getagentoverride) * [List Agentoverrides](/document/businessLogic/listagentoverrides) * [Update Agentoverride](/document/businessLogic/updateagentoverride) * [Create Agentoverride](/document/businessLogic/createagentoverride) * [Delete Agentoverride](/document/businessLogic/deleteagentoverride) * [List Toolcatalog](/document/businessLogic/listtoolcatalog) * [Get Toolcatalogentry](/document/businessLogic/gettoolcatalogentry) * [List Agentexecutions](/document/businessLogic/listagentexecutions) * [Get Agentexecution](/document/businessLogic/getagentexecution) --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## aifitapp-agenthub-service **Version:** `1.0.0` AI Agent Hub ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the AgentHub Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AgentHub Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the AgentHub Service via HTTP requests for purposes such as creating, updating, deleting and querying AgentHub objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the AgentHub Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the AgentHub service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | appaili-access-token| | Cookie | appaili-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the AgentHub service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the AgentHub service. This service is configured to listen for HTTP requests on port `3006`, 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` This service is accessible via the following environment-specific URLs: * **Preview:** `https://appaili.prw.mindbricks.com/agenthub-api` * **Staging:** `https://appaili-stage.mindbricks.co/agenthub-api` * **Production:** `https://appaili.mindbricks.co/agenthub-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the AgentHub service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `AgentHub` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `AgentHub` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `AgentHub` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources AgentHub service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### Sys_agentOverride resource *Resource Definition* : Runtime overrides for design-time agents. Null fields use the design default. *Sys_agentOverride Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **agentName** | String | | | *Design-time agent name this override applies to.* | | **provider** | String | | | *Override AI provider (e.g., openai, anthropic).* | | **model** | String | | | *Override model name.* | | **systemPrompt** | Text | | | *Override system prompt.* | | **temperature** | Double | | | *Override temperature (0-2).* | | **maxTokens** | Integer | | | *Override max tokens.* | | **responseFormat** | String | | | *Override response format (text/json).* | | **selectedTools** | Object | | | *Array of tool names from the catalog that this agent can use.* | | **guardrails** | Object | | | *Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.* | | **enabled** | Boolean | | | *Enable or disable this agent.* | | **updatedBy** | ID | | | *User who last updated this override.* | ### Sys_agentExecution resource *Resource Definition* : Agent execution log. Records each agent invocation with input, output, and performance metrics. *Sys_agentExecution Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **agentName** | String | | | *Agent that was executed.* | | **agentType** | Enum | | | *Whether this was a design-time or dynamic agent.* | | **source** | Enum | | | *How the agent was triggered.* | | **userId** | ID | | | *User who triggered the execution.* | | **input** | Object | | | *Request input (truncated for large payloads).* | | **output** | Object | | | *Response output (truncated for large payloads).* | | **toolCalls** | Integer | | | *Number of tool calls made during execution.* | | **tokenUsage** | Object | | | *Token usage: { prompt, completion, total }.* | | **durationMs** | Integer | | | *Execution time in milliseconds.* | | **status** | Enum | | | *Execution status.* | | **error** | Text | | | *Error message if execution failed.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### agentType Enum Property *Property Definition* : Whether this was a design-time or dynamic agent.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **design** | `"design""` | 0 | | **dynamic** | `"dynamic""` | 1 | ##### source Enum Property *Property Definition* : How the agent was triggered.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **rest** | `"rest""` | 0 | | **sse** | `"sse""` | 1 | | **kafka** | `"kafka""` | 2 | | **agent** | `"agent""` | 3 | ##### status Enum Property *Property Definition* : Execution status.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **success** | `"success""` | 0 | | **error** | `"error""` | 1 | | **timeout** | `"timeout""` | 2 | ### Sys_toolCatalog resource *Resource Definition* : Cached tool catalog discovered from project services. Refreshed periodically. *Sys_toolCatalog Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **toolName** | String | | | *Full tool name (e.g., service:apiName).* | | **serviceName** | String | | | *Source service name.* | | **description** | Text | | | *Tool description.* | | **parameters** | Object | | | *JSON Schema of tool parameters.* | | **lastRefreshed** | Date | | | *When this tool was last discovered/refreshed.* | ## Business Api ### `Get Agentoverride` API **[Default get API]** — This is the designated default `get` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `getAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'GET', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentoverrides` API **[Default list API]** — This is the designated default `list` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentOverrides` API REST controller can be triggered via the following route: `/v1/agentoverrides` **Rest Request Parameters** The `listAgentOverrides` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverrides** ```js axios({ method: 'GET', url: '/v1/agentoverrides', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverrides", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentOverrides": [ { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Agentoverride` API **[Default update API]** — This is the designated default `update` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `updateAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `updateAgentOverride` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | | provider | String | | request.body?.["provider"] | | model | String | | request.body?.["model"] | | systemPrompt | Text | | request.body?.["systemPrompt"] | | temperature | Double | | request.body?.["temperature"] | | maxTokens | Integer | | request.body?.["maxTokens"] | | responseFormat | String | | request.body?.["responseFormat"] | | selectedTools | Object | | request.body?.["selectedTools"] | | guardrails | Object | | request.body?.["guardrails"] | | enabled | Boolean | | request.body?.["enabled"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be updated **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **enabled** : Enable or disable this agent. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'PATCH', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", enabled:"Boolean", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Create Agentoverride` API **[Default create API]** — This is the designated default `create` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `createAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride` **Rest Request Parameters** The `createAgentOverride` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | agentName | String | true | request.body?.["agentName"] | | provider | String | false | request.body?.["provider"] | | model | String | false | request.body?.["model"] | | systemPrompt | Text | false | request.body?.["systemPrompt"] | | temperature | Double | false | request.body?.["temperature"] | | maxTokens | Integer | false | request.body?.["maxTokens"] | | responseFormat | String | false | request.body?.["responseFormat"] | | selectedTools | Object | false | request.body?.["selectedTools"] | | guardrails | Object | false | request.body?.["guardrails"] | **agentName** : Design-time agent name this override applies to. **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/agentoverride** ```js axios({ method: 'POST', url: '/v1/agentoverride', data: { agentName:"String", provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Delete Agentoverride` API **[Default delete API]** — This is the designated default `delete` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `deleteAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'DELETE', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `List Toolcatalog` API **[Default list API]** — This is the designated default `list` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listToolCatalog` API REST controller can be triggered via the following route: `/v1/toolcatalog` **Rest Request Parameters** **Filter Parameters** The `listToolCatalog` api supports 1 optional filter parameter for filtering list results: **serviceName** (`String`): Source service name. - Single (partial match, case-insensitive): `?serviceName=` - Multiple: `?serviceName=&serviceName=` - Null: `?serviceName=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalog** ```js axios({ method: 'GET', url: '/v1/toolcatalog', data: { }, params: { // Filter parameters (see Filter Parameters section above) // serviceName: '' // Filter by serviceName } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_toolCatalogs": [ { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Toolcatalogentry` API **[Default get API]** — This is the designated default `get` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getToolCatalogEntry` API REST controller can be triggered via the following route: `/v1/toolcatalogentry/:sys_toolCatalogId` **Rest Request Parameters** The `getToolCatalogEntry` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_toolCatalogId | ID | true | request.params?.["sys_toolCatalogId"] | **sys_toolCatalogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalogentry/:sys_toolCatalogId** ```js axios({ method: 'GET', url: `/v1/toolcatalogentry/${sys_toolCatalogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_toolCatalog": { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentexecutions` API **[Default list API]** — This is the designated default `list` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentExecutions` API REST controller can be triggered via the following route: `/v1/agentexecutions` **Rest Request Parameters** **Filter Parameters** The `listAgentExecutions` api supports 5 optional filter parameters for filtering list results: **agentName** (`String`): Agent that was executed. - Single (partial match, case-insensitive): `?agentName=` - Multiple: `?agentName=&agentName=` - Null: `?agentName=null` **agentType** (`Enum`): Whether this was a design-time or dynamic agent. - Single: `?agentType=` (case-insensitive) - Multiple: `?agentType=&agentType=` - Null: `?agentType=null` **source** (`Enum`): How the agent was triggered. - Single: `?source=` (case-insensitive) - Multiple: `?source=&source=` - Null: `?source=null` **userId** (`ID`): User who triggered the execution. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **status** (`Enum`): Execution status. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecutions** ```js axios({ method: 'GET', url: '/v1/agentexecutions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // agentName: '' // Filter by agentName // agentType: '' // Filter by agentType // source: '' // Filter by source // userId: '' // Filter by userId // status: '' // Filter by status } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecutions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentExecutions": [ { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Agentexecution` API **[Default get API]** — This is the designated default `get` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentExecution` API REST controller can be triggered via the following route: `/v1/agentexecution/:sys_agentExecutionId` **Rest Request Parameters** The `getAgentExecution` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentExecutionId | ID | true | request.params?.["sys_agentExecutionId"] | **sys_agentExecutionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecution/:sys_agentExecutionId** ```js axios({ method: 'GET', url: `/v1/agentexecution/${sys_agentExecutionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecution", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentExecution": { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- ## EVENT GUIDE # EVENT GUIDE ## aifitapp-agenthub-service AI Agent Hub ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. # Documentation Scope Welcome to the official documentation for the `AgentHub` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `AgentHub` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `AgentHub` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `AgentHub` objects. **Overview** This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples. # Authentication and Authorization Access to the `AgentHub` service's events is facilitated through the project's Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server. Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide. # Database Events Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic. Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service's scope, ensuring data consistency and syncronization across services. For example, while a business operation such as "approve membership" might generate a high-level business event like `membership-approved`, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as `dbevent-member-updated` and `dbevent-user-updated`, reflecting the granular changes at the database level. Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes. ## DbEvent sys_agentOverride-created **Event topic**: `appaili-agenthub-service-dbevent-sys_agentoverride-created` This event is triggered upon the creation of a `sys_agentOverride` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_agentOverride-updated **Event topic**: `appaili-agenthub-service-dbevent-sys_agentoverride-updated` Activation of this event follows the update of a `sys_agentOverride` data object. The payload contains the updated information under the `sys_agentOverride` attribute, along with the original data prior to update, labeled as `old_sys_agentOverride` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_agentOverride:{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_agentOverride:{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_agentOverride-deleted **Event topic**: `appaili-agenthub-service-dbevent-sys_agentoverride-deleted` This event announces the deletion of a `sys_agentOverride` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false} ``` ## DbEvent sys_agentExecution-created **Event topic**: `appaili-agenthub-service-dbevent-sys_agentexecution-created` This event is triggered upon the creation of a `sys_agentExecution` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_agentExecution-updated **Event topic**: `appaili-agenthub-service-dbevent-sys_agentexecution-updated` Activation of this event follows the update of a `sys_agentExecution` data object. The payload contains the updated information under the `sys_agentExecution` attribute, along with the original data prior to update, labeled as `old_sys_agentExecution` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_agentExecution:{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_agentExecution:{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_agentExecution-deleted **Event topic**: `appaili-agenthub-service-dbevent-sys_agentexecution-deleted` This event announces the deletion of a `sys_agentExecution` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false} ``` ## DbEvent sys_toolCatalog-created **Event topic**: `appaili-agenthub-service-dbevent-sys_toolcatalog-created` This event is triggered upon the creation of a `sys_toolCatalog` data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod. **Event payload**: ```json {"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_toolCatalog-updated **Event topic**: `appaili-agenthub-service-dbevent-sys_toolcatalog-updated` Activation of this event follows the update of a `sys_toolCatalog` data object. The payload contains the updated information under the `sys_toolCatalog` attribute, along with the original data prior to update, labeled as `old_sys_toolCatalog` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_toolCatalog:{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, sys_toolCatalog:{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent sys_toolCatalog-deleted **Event topic**: `appaili-agenthub-service-dbevent-sys_toolcatalog-deleted` This event announces the deletion of a `sys_toolCatalog` data object, covering both hard deletions (permanent removal) and soft deletions (where the `isActive` attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an `isActive` status of false for soft deletions. **Event payload**: ```json {"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false} ``` # ElasticSearch Index Events Within the `AgentHub` service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects. These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries. It's noteworthy that some services may augment another service's index by appending to the entity’s `extends` object. In such scenarios, an `*-extended` event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID. This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications. ## Index Event sys_agentoverride-created **Event topic**: `elastic-index-aifitapp_sys_agentoverride-created` **Event payload**: ```json {"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_agentoverride-updated **Event topic**: `elastic-index-aifitapp_sys_agentoverride-created` **Event payload**: ```json {"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_agentoverride-deleted **Event topic**: `elastic-index-aifitapp_sys_agentoverride-deleted` **Event payload**: ```json {"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_agentoverride-extended **Event topic**: `elastic-index-aifitapp_sys_agentoverride-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event agentoverride-retrived **Event topic** : `appaili-agenthub-service-agentoverride-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverrides-listed **Event topic** : `appaili-agenthub-service-agentoverrides-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverrides` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverrides`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event agentoverride-updated **Event topic** : `appaili-agenthub-service-agentoverride-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverride-created **Event topic** : `appaili-agenthub-service-agentoverride-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverride-deleted **Event topic** : `appaili-agenthub-service-agentoverride-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event toolcatalog-listed **Event topic** : `appaili-agenthub-service-toolcatalog-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_toolCatalogs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_toolCatalogs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event toolcatalogentry-retrived **Event topic** : `appaili-agenthub-service-toolcatalogentry-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_toolCatalog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_toolCatalog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentexecutions-listed **Event topic** : `appaili-agenthub-service-agentexecutions-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentExecutions` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentExecutions`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event agentexecution-retrived **Event topic** : `appaili-agenthub-service-agentexecution-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentExecution` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentExecution`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Index Event sys_agentexecution-created **Event topic**: `elastic-index-aifitapp_sys_agentexecution-created` **Event payload**: ```json {"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_agentexecution-updated **Event topic**: `elastic-index-aifitapp_sys_agentexecution-created` **Event payload**: ```json {"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_agentexecution-deleted **Event topic**: `elastic-index-aifitapp_sys_agentexecution-deleted` **Event payload**: ```json {"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_agentexecution-extended **Event topic**: `elastic-index-aifitapp_sys_agentexecution-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event agentoverride-retrived **Event topic** : `appaili-agenthub-service-agentoverride-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverrides-listed **Event topic** : `appaili-agenthub-service-agentoverrides-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverrides` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverrides`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event agentoverride-updated **Event topic** : `appaili-agenthub-service-agentoverride-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverride-created **Event topic** : `appaili-agenthub-service-agentoverride-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverride-deleted **Event topic** : `appaili-agenthub-service-agentoverride-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event toolcatalog-listed **Event topic** : `appaili-agenthub-service-toolcatalog-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_toolCatalogs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_toolCatalogs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event toolcatalogentry-retrived **Event topic** : `appaili-agenthub-service-toolcatalogentry-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_toolCatalog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_toolCatalog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentexecutions-listed **Event topic** : `appaili-agenthub-service-agentexecutions-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentExecutions` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentExecutions`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event agentexecution-retrived **Event topic** : `appaili-agenthub-service-agentexecution-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentExecution` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentExecution`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Index Event sys_toolcatalog-created **Event topic**: `elastic-index-aifitapp_sys_toolcatalog-created` **Event payload**: ```json {"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_toolcatalog-updated **Event topic**: `elastic-index-aifitapp_sys_toolcatalog-created` **Event payload**: ```json {"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_toolcatalog-deleted **Event topic**: `elastic-index-aifitapp_sys_toolcatalog-deleted` **Event payload**: ```json {"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event sys_toolcatalog-extended **Event topic**: `elastic-index-aifitapp_sys_toolcatalog-extended` **Event payload**: ```js { id: id, extends: { [extendName]: "Object", [extendName + "_count"]: "Number", }, } ``` # Route Events Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route's execution, is more pertinent. Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity's data but also route-specific metrics, such as the executing user's permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic. The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service's functional outcomes. ## Route Event agentoverride-retrived **Event topic** : `appaili-agenthub-service-agentoverride-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverrides-listed **Event topic** : `appaili-agenthub-service-agentoverrides-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverrides` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverrides`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event agentoverride-updated **Event topic** : `appaili-agenthub-service-agentoverride-updated` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverride-created **Event topic** : `appaili-agenthub-service-agentoverride-created` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentoverride-deleted **Event topic** : `appaili-agenthub-service-agentoverride-deleted` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentOverride` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentOverride`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}} ``` ## Route Event toolcatalog-listed **Event topic** : `appaili-agenthub-service-toolcatalog-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_toolCatalogs` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_toolCatalogs`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event toolcatalogentry-retrived **Event topic** : `appaili-agenthub-service-toolcatalogentry-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_toolCatalog` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_toolCatalog`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` ## Route Event agentexecutions-listed **Event topic** : `appaili-agenthub-service-agentexecutions-listed` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentExecutions` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentExecutions`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event agentexecution-retrived **Event topic** : `appaili-agenthub-service-agentexecution-retrived` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `sys_agentExecution` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_agentExecution`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}} ``` # Copyright All sources, documents and other digital materials are copyright of . # About Us For more information please visit our website: . . . --- ## Data Objects ### Service Design Specification - Object Design for sys_agentOverride # Service Design Specification - Object Design for sys_agentOverride **aifitapp-agenthub-service** documentation ## Document Overview This document outlines the object design for the `sys_agentOverride` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## sys_agentOverride Data Object ### Object Overview **Description:** Runtime overrides for design-time agents. Null fields use the design default. 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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `agentName` | String | Yes | Design-time agent name this override applies to. | | `provider` | String | No | Override AI provider (e.g., openai, anthropic). | | `model` | String | No | Override model name. | | `systemPrompt` | Text | No | Override system prompt. | | `temperature` | Double | No | Override temperature (0-2). | | `maxTokens` | Integer | No | Override max tokens. | | `responseFormat` | String | No | Override response format (text/json). | | `selectedTools` | Object | No | Array of tool names from the catalog that this agent can use. | | `guardrails` | Object | No | Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. | | `enabled` | Boolean | Yes | Enable or disable this agent. | | `updatedBy` | ID | No | User who last updated this override. | * 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. - **agentName**: 'default' - **enabled**: true ### 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. - **enabled**: Will be created with value `true` ### Constant Properties `agentName` 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 `agentName` `provider` `model` `systemPrompt` `temperature` `maxTokens` `responseFormat` `selectedTools` `guardrails` `enabled` `updatedBy` 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 `agentName` `enabled` 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 `agentName` `enabled` 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 `agentName` 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. ### Session Data Properties `updatedBy` 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. - **updatedBy**: ID property will be mapped to the session parameter `userId`. --- ### Service Design Specification - Object Design for sys_agentExecution # Service Design Specification - Object Design for sys_agentExecution **aifitapp-agenthub-service** documentation ## Document Overview This document outlines the object design for the `sys_agentExecution` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## sys_agentExecution Data Object ### Object Overview **Description:** Agent execution log. Records each agent invocation with input, output, and performance metrics. 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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `agentName` | String | Yes | Agent that was executed. | | `agentType` | Enum | Yes | Whether this was a design-time or dynamic agent. | | `source` | Enum | Yes | How the agent was triggered. | | `userId` | ID | No | User who triggered the execution. | | `input` | Object | No | Request input (truncated for large payloads). | | `output` | Object | No | Response output (truncated for large payloads). | | `toolCalls` | Integer | No | Number of tool calls made during execution. | | `tokenUsage` | Object | No | Token usage: { prompt, completion, total }. | | `durationMs` | Integer | No | Execution time in milliseconds. | | `status` | Enum | Yes | Execution status. | | `error` | Text | No | Error message if execution failed. | * 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. - **agentName**: 'default' - **agentType**: "design" - **source**: "rest" - **status**: "success" ### Constant Properties `agentName` `agentType` `source` `userId` `input` `output` `toolCalls` `tokenUsage` `durationMs` `status` `error` 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 `agentName` `agentType` `source` `userId` `input` `output` `toolCalls` `tokenUsage` `durationMs` `status` `error` 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. - **agentType**: [design, dynamic] - **source**: [rest, sse, kafka, agent] - **status**: [success, error, timeout] ### Elastic Search Indexing `agentName` `agentType` `source` `userId` `toolCalls` `durationMs` `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 `agentName` `agentType` `source` `userId` `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. ### Filter Properties `agentName` `agentType` `source` `userId` `status` 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. - **agentName**: String has a filter named `agentName` - **agentType**: Enum has a filter named `agentType` - **source**: Enum has a filter named `source` - **userId**: ID has a filter named `userId` - **status**: Enum has a filter named `status` --- ### Service Design Specification - Object Design for sys_toolCatalog # Service Design Specification - Object Design for sys_toolCatalog **aifitapp-agenthub-service** documentation ## Document Overview This document outlines the object design for the `sys_toolCatalog` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## sys_toolCatalog Data Object ### Object Overview **Description:** Cached tool catalog discovered from project services. Refreshed periodically. 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:** accessProtected — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `toolName` | String | Yes | Full tool name (e.g., service:apiName). | | `serviceName` | String | Yes | Source service name. | | `description` | Text | No | Tool description. | | `parameters` | Object | No | JSON Schema of tool parameters. | | `lastRefreshed` | Date | No | When this tool was last discovered/refreshed. | * 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. - **toolName**: 'default' - **serviceName**: 'default' ### Auto Update Properties `toolName` `serviceName` `description` `parameters` `lastRefreshed` 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 `toolName` `serviceName` `description` 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 `toolName` `serviceName` 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 `toolName` 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. ### Filter Properties `serviceName` 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. - **serviceName**: String has a filter named `serviceName` --- ## Business APIs ### Business API Design Specification - `Get Agentoverride` # Business API Design Specification - `Get Agentoverride` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getAgentOverride` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getAgentOverride` Business API is designed to handle a `get` operation on the `Sys_agentOverride` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentoverride-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getAgentOverride` Business API includes a REST controller that can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getAgentOverride` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAgentOverride` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_agentOverrideId` | `ID` | `Yes` | `-` | `urlpath` | `sys_agentOverrideId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getAgentOverride` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[3].businessLogic[0].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getAgentOverride` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'GET', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentOverride`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `List Agentoverrides` # Business API Design Specification - `List Agentoverrides` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listAgentOverrides` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listAgentOverrides` Business API is designed to handle a `list` operation on the `Sys_agentOverride` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentoverrides-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listAgentOverrides` Business API includes a REST controller that can be triggered via the following route: `/v1/agentoverrides` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listAgentOverrides` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAgentOverrides` Business API does not require any parameters to be provided from the controllers. ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listAgentOverrides` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js null ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listAgentOverrides` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/agentoverrides** ```js axios({ method: 'GET', url: '/v1/agentoverrides', data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentOverrides`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverrides", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentOverrides": [ { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Update Agentoverride` # Business API Design Specification - `Update Agentoverride` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `updateAgentOverride` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `updateAgentOverride` Business API is designed to handle a `update` operation on the `Sys_agentOverride` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentoverride-updated` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `updateAgentOverride` Business API includes a REST controller that can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `updateAgentOverride` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateAgentOverride` Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_agentOverrideId` | `ID` | `Yes` | `-` | `urlpath` | `sys_agentOverrideId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `provider` | `String` | `No` | `-` | `body` | `provider` | | **Description:** | Override AI provider (e.g., openai, anthropic). | | | | | | | | | | | | | `model` | `String` | `No` | `-` | `body` | `model` | | **Description:** | Override model name. | | | | | | | | | | | | | `systemPrompt` | `Text` | `No` | `-` | `body` | `systemPrompt` | | **Description:** | Override system prompt. | | | | | | | | | | | | | `temperature` | `Double` | `No` | `-` | `body` | `temperature` | | **Description:** | Override temperature (0-2). | | | | | | | | | | | | | `maxTokens` | `Integer` | `No` | `-` | `body` | `maxTokens` | | **Description:** | Override max tokens. | | | | | | | | | | | | | `responseFormat` | `String` | `No` | `-` | `body` | `responseFormat` | | **Description:** | Override response format (text/json). | | | | | | | | | | | | | `selectedTools` | `Object` | `No` | `-` | `body` | `selectedTools` | | **Description:** | Array of tool names from the catalog that this agent can use. | | | | | | | | | | | | | `guardrails` | `Object` | `No` | `-` | `body` | `guardrails` | | **Description:** | Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. | | | | | | | | | | | | | `enabled` | `Boolean` | `No` | `-` | `body` | `enabled` | | **Description:** | Enable or disable this agent. | | | | | | | | | | | | | `updatedBy` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | User who last updated this override. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `updateAgentOverride` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[3].businessLogic[2].whereClause.fullWhereClause"}) ``` ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { provider: this.provider, model: this.model, systemPrompt: this.systemPrompt, temperature: this.temperature, maxTokens: this.maxTokens, responseFormat: this.responseFormat, selectedTools: this.selectedTools ? (typeof this.selectedTools == 'string' ? JSON.parse(this.selectedTools) : this.selectedTools) : null, guardrails: this.guardrails ? (typeof this.guardrails == 'string' ? JSON.parse(this.guardrails) : this.guardrails) : null, enabled: this.enabled, updatedBy: this.updatedBy, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context. --- ### [4] Step : checkParameters Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met. --- ### [5] Step : checkBasicAuth Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the existing record from the database and writes it to the context for validation or enrichment. --- ### [8] Step : checkInstance Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks. --- ### [9] Step : buildDataClause Manager prepares the data clause for the update, applying transformations or enhancements before persisting. You can use the following settings to change some behavior of this step. `dataClause` --- ### [10] Step : mainUpdateOperation Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured. --- ### [11] Step : buildOutput Manager assembles the response object from the update result, masking fields or injecting additional metadata. --- ### [12] Step : sendResponse Manager sends the response back to the controller for delivery to the client. --- ### [13] Step : raiseApiEvent Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `updateAgentOverride` api has got 10 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | | provider | String | | request.body?.["provider"] | | model | String | | request.body?.["model"] | | systemPrompt | Text | | request.body?.["systemPrompt"] | | temperature | Double | | request.body?.["temperature"] | | maxTokens | Integer | | request.body?.["maxTokens"] | | responseFormat | String | | request.body?.["responseFormat"] | | selectedTools | Object | | request.body?.["selectedTools"] | | guardrails | Object | | request.body?.["guardrails"] | | enabled | Boolean | | request.body?.["enabled"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'PATCH', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", enabled:"Boolean", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentOverride`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `Create Agentoverride` # Business API Design Specification - `Create Agentoverride` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `createAgentOverride` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `createAgentOverride` Business API is designed to handle a `create` operation on the `Sys_agentOverride` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentoverride-created` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `createAgentOverride` Business API includes a REST controller that can be triggered via the following route: `/v1/agentoverride` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `createAgentOverride` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAgentOverride` Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_agentOverrideId` | `ID` | `No` | `-` | `body` | `sys_agentOverrideId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `agentName` | `String` | `Yes` | `-` | `body` | `agentName` | | **Description:** | Design-time agent name this override applies to. | | | | | | | | | | | | | `provider` | `String` | `No` | `-` | `body` | `provider` | | **Description:** | Override AI provider (e.g., openai, anthropic). | | | | | | | | | | | | | `model` | `String` | `No` | `-` | `body` | `model` | | **Description:** | Override model name. | | | | | | | | | | | | | `systemPrompt` | `Text` | `No` | `-` | `body` | `systemPrompt` | | **Description:** | Override system prompt. | | | | | | | | | | | | | `temperature` | `Double` | `No` | `-` | `body` | `temperature` | | **Description:** | Override temperature (0-2). | | | | | | | | | | | | | `maxTokens` | `Integer` | `No` | `-` | `body` | `maxTokens` | | **Description:** | Override max tokens. | | | | | | | | | | | | | `responseFormat` | `String` | `No` | `-` | `body` | `responseFormat` | | **Description:** | Override response format (text/json). | | | | | | | | | | | | | `selectedTools` | `Object` | `No` | `-` | `body` | `selectedTools` | | **Description:** | Array of tool names from the catalog that this agent can use. | | | | | | | | | | | | | `guardrails` | `Object` | `No` | `-` | `body` | `guardrails` | | **Description:** | Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. | | | | | | | | | | | | | `updatedBy` | `ID` | `No` | `-` | `session` | `userId` | | **Description:** | User who last updated this override. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `createAgentOverride` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Data Clause Defines custom field-value assignments used to modify or augment the default payload for `create` and `update` operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings. **Custom Data Clause Override** *No custom data clause override configured* **Actual Data Clause** The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager. ```js { id: this.sys_agentOverrideId, agentName: this.agentName, provider: this.provider, model: this.model, systemPrompt: this.systemPrompt, temperature: this.temperature, maxTokens: this.maxTokens, responseFormat: this.responseFormat, selectedTools: this.selectedTools ? (typeof this.selectedTools == 'string' ? JSON.parse(this.selectedTools) : this.selectedTools) : null, guardrails: this.guardrails ? (typeof this.guardrails == 'string' ? JSON.parse(this.guardrails) : this.guardrails) : null, updatedBy: this.updatedBy, } ``` ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing. --- ### [4] Step : checkParameters Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails. --- ### [5] Step : checkBasicAuth Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildDataClause Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency. You can use the following settings to change some behavior of this step. `dataClause` --- ### [7] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [8] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [9] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [10] Step : raiseApiEvent Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `createAgentOverride` api has got 9 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | agentName | String | true | request.body?.["agentName"] | | provider | String | false | request.body?.["provider"] | | model | String | false | request.body?.["model"] | | systemPrompt | Text | false | request.body?.["systemPrompt"] | | temperature | Double | false | request.body?.["temperature"] | | maxTokens | Integer | false | request.body?.["maxTokens"] | | responseFormat | String | false | request.body?.["responseFormat"] | | selectedTools | Object | false | request.body?.["selectedTools"] | | guardrails | Object | false | request.body?.["guardrails"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/agentoverride** ```js axios({ method: 'POST', url: '/v1/agentoverride', data: { agentName:"String", provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentOverride`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `Delete Agentoverride` # Business API Design Specification - `Delete Agentoverride` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `deleteAgentOverride` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `deleteAgentOverride` Business API is designed to handle a `delete` operation on the `Sys_agentOverride` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentoverride-deleted` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `deleteAgentOverride` Business API includes a REST controller that can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `deleteAgentOverride` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteAgentOverride` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_agentOverrideId` | `ID` | `Yes` | `-` | `urlpath` | `sys_agentOverrideId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `deleteAgentOverride` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[3].businessLogic[4].whereClause.fullWhereClause"}) ``` ## Delete Options Use these options to set `delete` specific settings. **useSoftDelete**: If true, the record will be marked as deleted `(isActive: false)` instead of removed. The implementation depends on the data object’s soft delete configuration. ## Business Logic Workflow ### [1] Step : startBusinessApi Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing. --- ### [4] Step : checkParameters Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails. --- ### [5] Step : checkBasicAuth Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : fetchInstance Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks. --- ### [8] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [9] Step : mainDeleteOperation Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration. You can use the following settings to change some behavior of this step. `deleteOptions` --- ### [10] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [11] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [12] Step : raiseApiEvent Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `deleteAgentOverride` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'DELETE', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentOverride`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` --- ### Business API Design Specification - `List Toolcatalog` # Business API Design Specification - `List Toolcatalog` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listToolCatalog` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listToolCatalog` Business API is designed to handle a `list` operation on the `Sys_toolCatalog` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `toolcatalog-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listToolCatalog` Business API includes a REST controller that can be triggered via the following route: `/v1/toolcatalog` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listToolCatalog` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listToolCatalog` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listToolCatalog` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `serviceName` Filter **Type:** `String` **Description:** Source service name. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?serviceName=` (matches any string containing the value, case-insensitive) - Multiple values: `?serviceName=&serviceName=` (matches records containing any of the values) - Null check: `?serviceName=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/toolcatalog?serviceName=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/toolcatalog?serviceName=laptop&serviceName=phone&serviceName=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/toolcatalog?serviceName=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listToolCatalog` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js null ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listToolCatalog` api has 1 filter parameter available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | serviceName | String | No | Source service name. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/toolcatalog** ```js axios({ method: 'GET', url: '/v1/toolcatalog', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // serviceName: '' // Filter by serviceName } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_toolCatalogs`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_toolCatalogs": [ { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Get Toolcatalogentry` # Business API Design Specification - `Get Toolcatalogentry` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getToolCatalogEntry` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getToolCatalogEntry` Business API is designed to handle a `get` operation on the `Sys_toolCatalog` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `toolcatalogentry-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getToolCatalogEntry` Business API includes a REST controller that can be triggered via the following route: `/v1/toolcatalogentry/:sys_toolCatalogId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getToolCatalogEntry` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getToolCatalogEntry` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_toolCatalogId` | `ID` | `Yes` | `-` | `urlpath` | `sys_toolCatalogId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getToolCatalogEntry` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.sys_toolCatalogId}), {"path":"services[3].businessLogic[6].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getToolCatalogEntry` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_toolCatalogId | ID | true | request.params?.["sys_toolCatalogId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/toolcatalogentry/:sys_toolCatalogId** ```js axios({ method: 'GET', url: `/v1/toolcatalogentry/${sys_toolCatalogId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_toolCatalog`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_toolCatalog": { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- ### Business API Design Specification - `List Agentexecutions` # Business API Design Specification - `List Agentexecutions` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `listAgentExecutions` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `listAgentExecutions` Business API is designed to handle a `list` operation on the `Sys_agentExecution` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentexecutions-listed` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `listAgentExecutions` Business API includes a REST controller that can be triggered via the following route: `/v1/agentexecutions` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `listAgentExecutions` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAgentExecutions` Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Filter Parameters The `listAgentExecutions` api supports 5 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `agentName` Filter **Type:** `String` **Description:** Agent that was executed. **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?agentName=` (matches any string containing the value, case-insensitive) - Multiple values: `?agentName=&agentName=` (matches records containing any of the values) - Null check: `?agentName=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/agentexecutions?agentName=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/agentexecutions?agentName=laptop&agentName=phone&agentName=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/agentexecutions?agentName=null ``` #### `agentType` Filter **Type:** `Enum` **Description:** Whether this was a design-time or dynamic agent. **Location:** Query Parameter **Usage:** - Single value: `?agentType=` (case-insensitive) - Multiple values: `?agentType=&agentType=` - Null check: `?agentType=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/agentexecutions?agentType=active // Get records with multiple enum values (use multiple parameters) GET /v1/agentexecutions?agentType=active&agentType=pending // Get records without this field GET /v1/agentexecutions?agentType=null ``` #### `source` Filter **Type:** `Enum` **Description:** How the agent was triggered. **Location:** Query Parameter **Usage:** - Single value: `?source=` (case-insensitive) - Multiple values: `?source=&source=` - Null check: `?source=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/agentexecutions?source=active // Get records with multiple enum values (use multiple parameters) GET /v1/agentexecutions?source=active&source=pending // Get records without this field GET /v1/agentexecutions?source=null ``` #### `userId` Filter **Type:** `ID` **Description:** User who triggered the execution. **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?userId=` - Multiple values: `?userId=&userId=` - Null check: `?userId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/agentexecutions?userId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/agentexecutions?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/agentexecutions?userId=null ``` #### `status` Filter **Type:** `Enum` **Description:** Execution status. **Location:** Query Parameter **Usage:** - Single value: `?status=` (case-insensitive) - Multiple values: `?status=&status=` - Null check: `?status=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/agentexecutions?status=active // Get records with multiple enum values (use multiple parameters) GET /v1/agentexecutions?status=active&status=pending // Get records without this field GET /v1/agentexecutions?status=null ``` ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `listAgentExecutions` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js null ``` ## List Options Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records. **List Sort By** Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc). Specific sort order is not configure, natural order (ascending id) will be used. **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. *The list is not grouped.* **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. **Permission Filter** Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user's OBAC or ABAC permissions. *Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.* ## Pagination Options Contains settings to configure pagination behavior for `list` APIs. Includes options like page size, offset, cursor support, and total count inclusion. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query. --- ### [4] Step : checkParameters Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency. --- ### [5] Step : checkBasicAuth Performs role-based access checks and applies dynamic membership or session-based restrictions. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Constructs the main query WHERE clause and applies optional filters or scoped access controls. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainListOperation Executes the paginated database query, retrieves the list, and stores results in context for enrichment. You can use the following settings to change some behavior of this step. `selectClause`, `listOptions`, `paginationOptions` --- ### [8] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [9] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [10] Step : raiseApiEvent Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `listAgentExecutions` api has 5 filter parameters available for filtering list results. See the [Filter Parameters](#filter-parameters) section above for detailed usage examples. | Filter Parameter | Type | Array Property | Description | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | agentName | String | No | Agent that was executed. | | agentType | Enum | No | Whether this was a design-time or dynamic agent. | | source | Enum | No | How the agent was triggered. | | userId | ID | No | User who triggered the execution. | | status | Enum | No | Execution status. | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/agentexecutions** ```js axios({ method: 'GET', url: '/v1/agentexecutions', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // agentName: '' // Filter by agentName // agentType: '' // Filter by agentType // source: '' // Filter by source // userId: '' // Filter by userId // status: '' // Filter by status } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentExecutions`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecutions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentExecutions": [ { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Get Agentexecution` # Business API Design Specification - `Get Agentexecution` A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic. While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized. This document provides an in-depth explanation of the architectural design of the `getAgentExecution` Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side. ## Main Data Object and CRUD Operation The `getAgentExecution` Business API is designed to handle a `get` operation on the `Sys_agentExecution` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Options * **Auto Params** : `true` Determines whether input parameters should be auto-generated from the schema of the associated data object. Set to `false` if you want to define all input parameters manually. * **Raise Api Event** : `true` Indicates whether the Business API should emit an API-level event after successful execution. This is typically used for audit trails, analytics, or external integrations. The event will be emitted to the `agentexecution-retrived` Kafka Topic Note that the DB-Level events for `create`, `update` and `delete` operations will always be raised for internal reasons. * **Active Check** : `` Controls how the system checks if a record is active (not soft-deleted or inactive). Uses the `ApiCheckOption` to determine whether this is checked during the query or after fetching the instance. * **Read From Entity Cache** : `` If enabled, the API will attempt to read the target object from the Redis entity cache before querying the database. This can improve performance for frequently accessed records. ## API Controllers A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel. ### REST Controller The `getAgentExecution` Business API includes a REST controller that can be triggered via the following route: `/v1/agentexecution/:sys_agentExecutionId` By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the **Parameters** section. ### MCP Tool REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This `getAgentExecution` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAgentExecution` Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client. Business API parameters can be: * **Auto-generated by Mindbricks** — inferred from the CRUD type and the property definitions of the main data object when the `autoParameters` option is enabled. * **Custom parameters added by the architect** — these can supplement or override the auto-generated parameters. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `sys_agentExecutionId` | `ID` | `Yes` | `-` | `urlpath` | `sys_agentExecutionId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | ### Parameter Transformations Some parameters are post-processed using **transform scripts** after being read from the request but before validation or workflow execution. Only parameters with a `transform` script are listed below. *No parameters are transformed in this API.* ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `getAgentExecution` Business API. These checks are applied **after parameter validation** and before executing the main business logic. While these settings cover the most common scenarios, more **fine-grained or conditional access control**—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like `PermissionCheckAction`, `MembershipCheckAction`, or `ObjectPermissionCheckAction`. ### Login Requirement This API **requires login** (`loginRequired = true`). Requests from non-logged-in users will return a **401 Unauthorized** error. Login is necessary **but not sufficient**, as additional role, permission, or other authorization checks may still apply. --- ### Ownership Checks --- ### Role and Permission Settings - **Absolute roles** (bypass all auth checks): Users with any of the following roles will bypass all authentication and authorization checks, including ownership, membership, and standard role/permission checks: `[superAdmin]` --- ## Select Clause Specifies which fields will be selected from the main data object during a `get` or `list` operation. Leave blank to select all properties. This applies only to `get` and `list` type APIs.", `` ## Where Clause Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to `get`, `list`, `update`, and `delete` APIs. All API types except `list` are expected to affect a single record. *If nothing is configured for (get, update, delete) the id fields will be the select criteria.* **Select By**: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (`get`, `update`, `delete`), it defines how a unique record is located. In `list` APIs, it scopes the results to only entries matching the given values. Note that `selectBy` fields will be ignored if `fullWhereClause` is set. *The business api configuration has no `selectBy` setting.* **Full Where Clause** An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When `fullWhereClause` is set, `selectBy` is ignored, however additional selects will still be applied to final where clause. The business api configuration has no `fullWhereClause` setting. **Additional Clauses** A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly. The business api configuration has no additionalClauses setting. **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({id:this.sys_agentExecutionId}), {"path":"services[3].businessLogic[8].whereClause.fullWhereClause"}) ``` ## Get Options Use these options to set `get` specific settings. **setAsRead**: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed. No `setAsread` field-value pair is configured. ## Business Logic Workflow ### [1] Step : startBusinessApi Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution. You can use the following settings to change some behavior of this step. `apiOptions`, `restSettings`, `grpcSettings`, `kafkaSettings`, `sseSettings`, `cronSettings` --- ### [2] Step : readParameters Extracts parameters from request and Redis, applies defaults, and writes them to context. You can use the following settings to change some behavior of this step. `customParameters`, `redisParameters` --- ### [3] Step : transposeParameters Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones. --- ### [4] Step : checkParameters Validates required and custom parameters, enforcing business-specific rules and constraints. --- ### [5] Step : checkBasicAuth Performs login, role, and permission checks, and applies dynamic object-level access rules. You can use the following settings to change some behavior of this step. `authOptions` --- ### [6] Step : buildWhereClause Builds the WHERE clause for fetching the object and applies additional scoped filters if configured. You can use the following settings to change some behavior of this step. `whereClause` --- ### [7] Step : mainGetOperation Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks. You can use the following settings to change some behavior of this step. `selectClause`, `getOptions` --- ### [8] Step : checkInstance Performs instance-level validations, such as ownership, existence, or access conditions. --- ### [9] Step : buildOutput Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed. --- ### [10] Step : sendResponse Delivers the response to the controller for client delivery. --- ### [11] Step : raiseApiEvent Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured. --- ## Rest Usage ### Rest Client Parameters Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The `getAgentExecution` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentExecutionId | ID | true | request.params?.["sys_agentExecutionId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/agentexecution/:sys_agentExecutionId** ```js axios({ method: 'GET', url: `/v1/agentexecution/${sys_agentExecutionId}`, data: { }, params: { } }); ``` ### REST Response The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. For error handling, refer to the "Error Response" section. Following JSON represents the most comprehensive form of the **`sys_agentExecution`** object in the respones. However, some properties may be omitted based on the object's internal logic. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecution", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentExecution": { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` --- # Bff Service ## Service Design Specification # Service Design Specification **BFF Service Documentation** **Version:** `1.0.6` --- ## Scope This document provides a comprehensive architectural overview of the **BFF Service**, a Backend-for-Frontend layer designed to unify access to backend ElasticSearch indices and event-driven aggregation logic. The service offers a full REST API suite and listens to Kafka topics to synchronize enriched views. This document is intended for: * **Architects** ensuring integration patterns and event consistency. * **Developers** building on top of or consuming the BFF service. * **DevOps Engineers** responsible for deployment and environment setup. > For endpoint-level specifications, refer to the REST API Guide. > For listener-level behavior, refer to the Event API Guide. --- ## Service Settings * **Port**: Configurable via `HTTP_PORT`, default: `3000` * **ElasticSearch**: Primary storage and query engine * **Kafka Broker**: `KAFKA_BROKER` for aggregation sync * **Mindbricks Injected Interface**: Configured with `api-face` * **Dynamic REST Routes**: Powered via codegen with `/` structure --- ## API Routes Overview The BFF service exposes a dynamic REST API interface that provides full access to ElasticSearch indices. These include list, count, filter, and schema-based interactions for both stored and virtual views. For full documentation of REST routes, including supported methods and examples, refer to the **REST API Guide**. --- ## Kafka Event Listeners The BFF service listens to ElasticSearch-related Kafka topics to maintain enriched and denormalized indices. These listeners trigger view aggregation functions upon receiving `create`, `update`, or `delete` events for primary and related entities. For detailed behavior, payloads, and listener-to-function mappings, refer to the **Event Guide**. --- ## Aggregation Strategy Each view is either: * **Stored View**: materialized into a separate ElasticSearch index * **Virtual View**: dynamically aggregated on request For each stored view: * `viewNameAggregateData(id)` handles source rehydration * Aggregates are executed via `aggregateNameAggregateDataFromIndex()` * Stats via `statNameStatDataFromIndex()` Final document is saved to: `_` --- ## Middleware ### Error Handling * `ApiError` extends native error * `errorConverter` ensures consistent error format * `errorHandler` outputs error JSON with stack trace in development ### Request Validation * `validate()` uses Joi + custom schema per route * Filters and pagination are schema-validated * Filter operators supported: `eq`, `noteq`, `range`, `wildcard`, `match`, etc. ### Async Wrapper * `catchAsync(fn)` auto-handles exceptions in async route handlers --- ## Elasticsearch Utilities * **Index Management**: create, check, delete * **Document Operations**: get, create, update, delete * **Query Builders**: * `queryBuilder()` for filters * `searchBuilder()` for full-text queries * `aggBuilder()` for terms aggregations * **Multi-index search support** with `multiSearchBuilder()` * **Dynamic Schema Extraction** via `fieldBuilder()` --- ## Cron Repair Logic Runs periodically to ensure data integrity: * `runAllRepair()` triggers each `viewNameRepair()` * For each view: * Reads base index with `match_all` * Re-runs aggregation pipeline * Indexes final result into enriched view index --- ## Environment Variables | Variable | Description | | -------------------- | ---------------------------------- | | `HTTP_PORT` | Service port | | `KAFKA_BROKER` | Kafka broker host | | `ELASTIC_URL` | Elasticsearch base URL | | `CORS_ORIGIN` | Allowed frontend origin (optional) | | `NODE_ENV` | Environment (dev, prod) | | `SERVICE_URL` | Used for injected API face config | | `SERVICE_SHORT_NAME` | Used in injected auth URL | --- ## App Lifecycle 1. Loads env: `.env`, `.prod.env`, etc. 2. Bootstraps Express app with: * CORS setup * JSON + cookie parsers * Dynamic routes * Swagger and API Face 3. Starts: * Kafka listeners * Cron repair jobs * Full enrichment pipelines 4. Handles SIGINT to close server cleanly --- ## Testing Strategy ### Unit Tests * Aggregation methods per view * Joi schemas * Custom middleware (errors, async, pick) ### Integration Tests * REST APIs (mock Elastic) * Kafka event triggers → view enrichment ### Load Tests (Optional) * GET `/index/list` with filters * Event storm on Kafka topics * Cron job load verification --- --- ## REST API GUIDE # REST API GUIDE ## BFF SERVICE **Version:** `1.0.6` BFF service is a microservice that acts as a bridge between the client and the backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to. For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the BFF Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our BFF Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the BFF Service via HTTP requests for purposes such as listing, filtering, and searching data. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. **Beyond REST** It's important to note that the BFF Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. --- ## Resources ### Elastic Index Resource _Resource Definition_: A virtual resource representing dynamic search data from a specified index. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/:indexName/list` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-----------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ```

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property.

--- _Default access route_: _GET_ `/:indexName/list` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-----------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/${indexName}/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/:indexName/count` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/:indexName/count` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | q | String | No | query.q | ```js axios({ method: "GET", url: `/${indexName}/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/:indexName/schema` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | ```js axios({ method: "GET", url: `/${indexName}/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /:indexName/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | ```js axios({ method: "GET", url: `/${indexName}/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /:indexName/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/filters`, data: { filterName: "String", conditions: "Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /:indexName/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | filterId | String | Yes | path.param | ```js axios({ method: "DELETE", url: `/${indexName}/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/:indexName/:id` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/${indexName}/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/ConversationDetailView` **Example**: ```js axios({ method: "GET", url: `/ConversationDetailView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/ConversationDetailView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/ConversationDetailView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/UserWeightProgressView` **Example**: ```js axios({ method: "GET", url: `/UserWeightProgressView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/UserWeightProgressView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/UserWeightProgressView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/AdminUserOverviewView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/AdminUserOverviewView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/AdminUserOverviewView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/AdminUserOverviewView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/AdminUserOverviewView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/AdminUserOverviewView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/AdminUserOverviewView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/AdminUserOverviewView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/AdminUserOverviewView/schema` ```js axios({ method: "GET", url: `/AdminUserOverviewView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /AdminUserOverviewView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/AdminUserOverviewView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /AdminUserOverviewView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/AdminUserOverviewView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /AdminUserOverviewView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/AdminUserOverviewView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/AdminUserOverviewView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/AdminUserOverviewView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/MealPlanDetailView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/MealPlanDetailView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/MealPlanDetailView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/MealPlanDetailView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/MealPlanDetailView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/MealPlanDetailView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/MealPlanDetailView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/MealPlanDetailView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/MealPlanDetailView/schema` ```js axios({ method: "GET", url: `/MealPlanDetailView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /MealPlanDetailView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/MealPlanDetailView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /MealPlanDetailView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/MealPlanDetailView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /MealPlanDetailView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/MealPlanDetailView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/MealPlanDetailView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/MealPlanDetailView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/ModerationNotificationView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/ModerationNotificationView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/ModerationNotificationView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/ModerationNotificationView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/ModerationNotificationView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/ModerationNotificationView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/ModerationNotificationView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/ModerationNotificationView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/ModerationNotificationView/schema` ```js axios({ method: "GET", url: `/ModerationNotificationView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /ModerationNotificationView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/ModerationNotificationView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /ModerationNotificationView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/ModerationNotificationView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /ModerationNotificationView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/ModerationNotificationView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/ModerationNotificationView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/ModerationNotificationView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/SubscriptionNotificationView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/SubscriptionNotificationView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/SubscriptionNotificationView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/SubscriptionNotificationView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/SubscriptionNotificationView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/SubscriptionNotificationView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/SubscriptionNotificationView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/SubscriptionNotificationView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/SubscriptionNotificationView/schema` ```js axios({ method: "GET", url: `/SubscriptionNotificationView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /SubscriptionNotificationView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/SubscriptionNotificationView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /SubscriptionNotificationView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/SubscriptionNotificationView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /SubscriptionNotificationView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/SubscriptionNotificationView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/SubscriptionNotificationView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/SubscriptionNotificationView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/TrainingProgramDetailView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/TrainingProgramDetailView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/TrainingProgramDetailView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/TrainingProgramDetailView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/TrainingProgramDetailView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/TrainingProgramDetailView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/TrainingProgramDetailView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/TrainingProgramDetailView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/TrainingProgramDetailView/schema` ```js axios({ method: "GET", url: `/TrainingProgramDetailView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /TrainingProgramDetailView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/TrainingProgramDetailView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /TrainingProgramDetailView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/TrainingProgramDetailView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /TrainingProgramDetailView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/TrainingProgramDetailView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/TrainingProgramDetailView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/TrainingProgramDetailView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/UserDashboardView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/UserDashboardView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/UserDashboardView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/UserDashboardView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/UserDashboardView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/UserDashboardView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/UserDashboardView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/UserDashboardView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/UserDashboardView/schema` ```js axios({ method: "GET", url: `/UserDashboardView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /UserDashboardView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/UserDashboardView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /UserDashboardView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/UserDashboardView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /UserDashboardView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/UserDashboardView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/UserDashboardView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/UserDashboardView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- --- ## EVENT API GUIDE # EVENT API GUIDE ## BFF SERVICE The BFF service is a microservice that acts as a bridge between the client and backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to. For inquiries, feedback, or further information regarding the architecture, please direct your communication to: **Email**: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the BFF Service Event Listeners. This guide details the Kafka-based event listeners responsible for reacting to ElasticSearch index events. It describes listener responsibilities, the topics they subscribe to, and expected payloads. **Intended Audience** This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the BFF Service. It assumes familiarity with microservices architecture, the Kafka messaging system, and ElasticSearch. **Overview** Each ElasticSearch index operation (create, update, delete) emits a corresponding event to Kafka. These events are consumed by listeners responsible for executing aggregate functions to ensure index- and system-level consistency. ## Kafka Event Listeners ### Kafka Event Listener: user-created **Event Topic**: `elastic-index-appaili_user-created` When a `user` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `AdminUserOverviewViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-appaili_user-updated` When a `user` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `AdminUserOverviewViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-appaili>_user-deleted` When a `user` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `AdminUserOverviewViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-created **Event Topic**: `elastic-index-subscription-created` When a `subscription` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `subscriptionReAdminUserOverviewView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-updated **Event Topic**: `elastic-index-appaili>_subscription-updated` When a `subscription` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `subscriptionReAdminUserOverviewView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-deleted **Event Topic**: `elastic-index-appaili>_subscription-deleted` When a `subscription` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `subscriptionReAdminUserOverviewView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: moderationrecord-created **Event Topic**: `elastic-index-moderationrecord-created` When a `moderationrecord` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `moderationRecordsReAdminUserOverviewView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: moderationrecord-updated **Event Topic**: `elastic-index-appaili>_moderationrecord-updated` When a `moderationrecord` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `moderationRecordsReAdminUserOverviewView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: moderationrecord-deleted **Event Topic**: `elastic-index-appaili>_moderationrecord-deleted` When a `moderationrecord` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `moderationRecordsReAdminUserOverviewView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: userquota-created **Event Topic**: `elastic-index-userquota-created` When a `userquota` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userQuotaReAdminUserOverviewView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: userquota-updated **Event Topic**: `elastic-index-appaili>_userquota-updated` When a `userquota` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userQuotaReAdminUserOverviewView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: userquota-deleted **Event Topic**: `elastic-index-appaili>_userquota-deleted` When a `userquota` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userQuotaReAdminUserOverviewView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: mealplan-created **Event Topic**: `elastic-index-appaili_mealplan-created` When a `mealplan` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `MealPlanDetailViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: mealplan-updated **Event Topic**: `elastic-index-appaili_mealplan-updated` When a `mealplan` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `MealPlanDetailViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: mealplan-deleted **Event Topic**: `elastic-index-appaili>_mealplan-deleted` When a `mealplan` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `MealPlanDetailViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: planmeal-created **Event Topic**: `elastic-index-planmeal-created` When a `planmeal` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `mealsReMealPlanDetailView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: planmeal-updated **Event Topic**: `elastic-index-appaili>_planmeal-updated` When a `planmeal` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `mealsReMealPlanDetailView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: planmeal-deleted **Event Topic**: `elastic-index-appaili>_planmeal-deleted` When a `planmeal` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `mealsReMealPlanDetailView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-created **Event Topic**: `elastic-index-user-created` When a `user` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReMealPlanDetailView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-appaili>_user-updated` When a `user` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReMealPlanDetailView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-appaili>_user-deleted` When a `user` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReMealPlanDetailView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: moderationrecord-created **Event Topic**: `elastic-index-appaili_moderationrecord-created` When a `moderationrecord` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `ModerationNotificationViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: moderationrecord-updated **Event Topic**: `elastic-index-appaili_moderationrecord-updated` When a `moderationrecord` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `ModerationNotificationViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: moderationrecord-deleted **Event Topic**: `elastic-index-appaili>_moderationrecord-deleted` When a `moderationrecord` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `ModerationNotificationViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-created **Event Topic**: `elastic-index-user-created` When a `user` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReModerationNotificationView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-appaili>_user-updated` When a `user` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReModerationNotificationView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-appaili>_user-deleted` When a `user` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReModerationNotificationView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-created **Event Topic**: `elastic-index-appaili_subscription-created` When a `subscription` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `SubscriptionNotificationViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-updated **Event Topic**: `elastic-index-appaili_subscription-updated` When a `subscription` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `SubscriptionNotificationViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-deleted **Event Topic**: `elastic-index-appaili>_subscription-deleted` When a `subscription` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `SubscriptionNotificationViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-created **Event Topic**: `elastic-index-user-created` When a `user` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReSubscriptionNotificationView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-appaili>_user-updated` When a `user` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReSubscriptionNotificationView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-appaili>_user-deleted` When a `user` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReSubscriptionNotificationView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: trainingprogram-created **Event Topic**: `elastic-index-appaili_trainingprogram-created` When a `trainingprogram` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `TrainingProgramDetailViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: trainingprogram-updated **Event Topic**: `elastic-index-appaili_trainingprogram-updated` When a `trainingprogram` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `TrainingProgramDetailViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: trainingprogram-deleted **Event Topic**: `elastic-index-appaili>_trainingprogram-deleted` When a `trainingprogram` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `TrainingProgramDetailViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: programexercise-created **Event Topic**: `elastic-index-programexercise-created` When a `programexercise` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `exercisesReTrainingProgramDetailView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: programexercise-updated **Event Topic**: `elastic-index-appaili>_programexercise-updated` When a `programexercise` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `exercisesReTrainingProgramDetailView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: programexercise-deleted **Event Topic**: `elastic-index-appaili>_programexercise-deleted` When a `programexercise` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `exercisesReTrainingProgramDetailView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-created **Event Topic**: `elastic-index-user-created` When a `user` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReTrainingProgramDetailView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-appaili>_user-updated` When a `user` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReTrainingProgramDetailView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-appaili>_user-deleted` When a `user` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userInfoReTrainingProgramDetailView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-created **Event Topic**: `elastic-index-appaili_user-created` When a `user` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `UserDashboardViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-appaili_user-updated` When a `user` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `UserDashboardViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-appaili>_user-deleted` When a `user` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `UserDashboardViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-created **Event Topic**: `elastic-index-subscription-created` When a `subscription` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `subscriptionReUserDashboardView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-updated **Event Topic**: `elastic-index-appaili>_subscription-updated` When a `subscription` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `subscriptionReUserDashboardView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: subscription-deleted **Event Topic**: `elastic-index-appaili>_subscription-deleted` When a `subscription` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `subscriptionReUserDashboardView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: trainingprogram-created **Event Topic**: `elastic-index-trainingprogram-created` When a `trainingprogram` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `trainingProgramReUserDashboardView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: trainingprogram-updated **Event Topic**: `elastic-index-appaili>_trainingprogram-updated` When a `trainingprogram` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `trainingProgramReUserDashboardView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: trainingprogram-deleted **Event Topic**: `elastic-index-appaili>_trainingprogram-deleted` When a `trainingprogram` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `trainingProgramReUserDashboardView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: mealplan-created **Event Topic**: `elastic-index-mealplan-created` When a `mealplan` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `mealPlanReUserDashboardView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: mealplan-updated **Event Topic**: `elastic-index-appaili>_mealplan-updated` When a `mealplan` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `mealPlanReUserDashboardView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: mealplan-deleted **Event Topic**: `elastic-index-appaili>_mealplan-deleted` When a `mealplan` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `mealPlanReUserDashboardView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: userquota-created **Event Topic**: `elastic-index-userquota-created` When a `userquota` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userQuotaReUserDashboardView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: userquota-updated **Event Topic**: `elastic-index-appaili>_userquota-updated` When a `userquota` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userQuotaReUserDashboardView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: userquota-deleted **Event Topic**: `elastic-index-appaili>_userquota-deleted` When a `userquota` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `userQuotaReUserDashboardView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` --- # Notification Service ## Service Design Specification # Service Design Specification **Notification Service Documentation** **Version:** `1.0.12` --- ## Scope This document provides a comprehensive architectural overview of the **Notification Service**, which is responsible for sending multi-channel notifications via Email, SMS, and Push. The service supports both REST and gRPC interfaces and utilizes an event-driven architecture through Kafka. This document is intended for: * **Backend Developers** integrating notification capabilities. * **DevOps Engineers** deploying or monitoring the notification system. * **Architects** evaluating extensibility, observability, and scalability. > For detailed REST interface, refer to the \[REST API Guide]. > For Kafka-based publishing and consumption flows, refer to the \[Event API Guide]. --- ## Service Settings * **Port**: Configurable via `HTTP_PORT`, default: `3000` * **Primary Interfaces**: * REST over Express * gRPC over Proto3 * Kafka via event topics * **Database**: PostgreSQL (via Sequelize) * **Optional**: Redis (for caching or state sharing) * **Email/SMS/Push Provider Configuration**: Dynamically switchable via `.env` --- ## Interfaces Overview ### REST API Exposes endpoints to: * Register/unregister devices * Fetch user notifications * Send new notifications * Mark notifications as seen For full list and parameters, refer to the **REST API Guide**. ### gRPC API Defined via `notification.sender.proto`: * `SendNotice()` RPC triggers notification dispatch for all specified channels. * Used for inter-service communication where synchronous flow is preferred. ### Kafka Events * The service **publishes** to and **subscribes** from: * `-notification-email` * `-notification-push` * `-notification-sms` For event structure and consumption logic, refer to the **Event API Guide**. --- ## Provider Architecture Each channel (SMS, Email, Push) is pluggable using a provider pattern. Providers can be toggled via env vars. ### Email Providers * SendGrid * SMTP * AmazonSES * FakeProvider (for dev/test) ### Push Providers * Firebase (FCM) * OneSignal * AmazonSNS * FakeProvider ### SMS Providers * Twilio * AmazonSNS * NetGSM * Vonage * FakeProvider Each provider implements a common `send(payload)` method and logs delivery result. --- ## Storage Mode Notifications can be optionally stored in the PostgreSQL database if `STORED_NOTICE=true` and `notificationBody.isStored=true`. Stored data includes: * `userId`, `title`, `body` * `metadata` (JSON) * `isSeen` flag * `createdAt` / `updatedAt` timestamps --- ## Aggregation & Templating Notification body and title can be: * Directly passed as raw strings * Or dynamically populated via predefined templates: * `WELCOME` * `OTP` * `RESETPASSWORD` * `NONE` (no template) Template rendering supports interpolation with `metadata`. Separate template files exist for: * Email (HTML) * SMS (Text) * Push (structured JSON) --- ## Middleware ### Error Handling * `ApiError` used for standard error shaping * `errorConverter`, `errorHandler` used globally ### Validation * All routes use Joi schema validation * Validations available for: * Device registration * Notification send * Pagination and sort filters * Mark-as-seen by IDs ### Utilities * `pick()`: Selects allowed keys from request * `pagination()`: Sequelize-based paginated query utility --- ## Lifecycle & Boot Process 1. Loads configuration from `.env` using `dotenv` 2. Initializes: * Express HTTP Server * gRPC Server (if `GRPC_ACTIVE=true`) * Kafka listeners * Redis connection * PostgreSQL connection 3. Injects OpenAPI/Swagger via `api-face` 4. Registers REST routes and middleware 5. Launches any scheduled cron jobs 6. Handles graceful shutdown via `SIGINT` --- ## Environment Variables | Variable | Description | | ---------------------- | ----------------------------------- | | `HTTP_PORT` | Express HTTP port (default: 3000) | | `GRPC_PORT` | gRPC server port (default: 50051) | | `SERVICE_URL` | Used to build auth redirect paths | | `SERVICE_SHORT_NAME` | Used for auth hostname substitution | | `PG_USER`, `PG_PASS` | PostgreSQL credentials | | `REDIS_HOST` | Redis connection string | | `STORED_NOTICE` | Whether to persist notifications | | `SENDGRID_API_KEY` | SendGrid API token | | `SMTP_USER/PASS/PORT` | SMTP credentials | | `TWILIO_*`, `NETGSM_*` | SMS provider credentials | | `ONESIGNAL_API_KEY` | OneSignal Push key | --- ## Testing Strategy ### Unit Tests * Provider `.send()` methods * Templating with metadata * Validation schema boundaries ### Integration Tests * REST endpoint workflows * Kafka → Listener execution * gRPC request handling ### End-to-End (Optional) * Simulate a full pipeline: Send → Store → Fetch → Mark as Seen --- ## Observability & Logging * Each send call logs payload & result to console * Provider-specific errors include stack traces --- ## REST API GUIDE # REST API GUIDE ## NOTIFICATION SERVICE **Version:** `1.0.12` The Notification service is a microservice that allows sending notifications through SMS, Email, and Push channels. Providers can be configured dynamically through the `.env` file. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to. For inquiries, feedback, or further information regarding the architecture, please direct your communication to: **Email**: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Notification Service REST API. This document provides a comprehensive overview of the available endpoints, how they work, and how to use them efficiently. **Intended Audience** This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the Notification Service. It assumes familiarity with microservices architecture and RESTful APIs. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. **Beyond REST** It's important to note that the Notification Service also supports alternative methods of interaction, such as messaging via a Kafka message broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. --- ## Routes ### Route: Register Device _Route Definition_: Registers a device for a user. _Route Type_: create _Default access route_: _POST_ `/devices/register` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | device | Object | Yes | body | | userId | ID | Yes | req.userId | ```js axios({ method: "POST", url: `/devices/register`, data: { device:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Unregister Device _Route Definition_: Removes a registered device. _Route Type_: delete _Default access route_: _DELETE_ `/devices/unregister/:deviceId` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | deviceId | ID | Yes | path.param | | userId | ID | Yes | req.userId | ```js axios({ method: "DELETE", url: `/devices/unregister/${deviceId}`, data:{}, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Get Notifications _Route Definition_: Retrieves a paginated list of notifications. _Route Type_: get _Default access route_: _GET_ `/notifications` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy| | userId | ID | Yes | req.userId | ```js axios({ method: "GET", url: `/notifications`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Send Notification _Route Definition_: Sends a notification to specified recipients. _Route Type_: create _Default access route_: _POST_ `/notifications` ### Parameters | Parameter | Type | Required | Population | |---------------|--------|----------|------------| |notification | Object | Yes | body | ```js axios({ method: "POST", url: `/notifications`, data: { notification:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Mark Notifications as Seen _Route Definition_: Marks selected notifications as seen. _Route Type_: update _Default access route_: _POST_ `/notifications/seen` ### Parameters | Parameter | Type | Required | Population | |------------------ |--------|----------|------------| | notificationIds | Array | Yes | body | | userId | ID | Yes | req.userId | ```js axios({ method: "POST", url: `/notifications/seen`, data: { notificationIds:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. --- --- ## EVENT API GUIDE # EVENT API GUIDE ## NOTIFICATION SERVICE The Notification service is a microservice that allows sending notifications through SMS, Email, and Push channels. Providers can be configured dynamically through the `.env` file. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to. For inquiries, feedback, or further information regarding the architecture, please direct your communication to: **Email**: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Notification Service Event Publishers and Listeners. This document provides a comprehensive overview of the event-driven architecture employed in the Notification Service, detailing the various events that are published and consumed within the system. **Intended Audience** This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the Notification Service. It assumes familiarity with microservices architecture and the Kafka messaging system. **Overview** This document outlines the key components of the Notification Service's event-driven architecture, including the events that are published and consumed, the Kafka topics used, and the expected payloads for each event. It serves as a reference guide for understanding how events flow through the system and how different components interact with each other. ## Kafka Event Publishers ### Kafka Event Publisher: sendEmailNotification **Event Topic**: `appaili-notification-service-notification-email` When a notification is sent through the Email channel, this publisher is responsible for sending the notification to the Kafka topic `appaili-notification-service-notification-email`. The payload of the event includes the necessary information for sending the email, such as recipient details, subject, and message body. ### Kafka Event Publisher: sendPushNotification **Event Topic**: `appaili-notification-service-notification-push` When a notification is sent through the Push channel, this publisher is responsible for sending the notification to the Kafka topic `appaili-notification-service-notification-push`. The payload of the event includes the necessary information for sending the push notification, such as recipient details, title, and message body. ### Kafka Event Publisher: sendSmsNotification **Event Topic**: appaili-notification-service-notification-sms` When a notification is sent through the SMS channel, this publisher is responsible for sending the notification to the Kafka topic `appaili-notification-service-notification-sms`. The payload of the event includes the necessary information for sending the SMS, such as recipient details and message body. ## Kafka Event Listeners ### Kafka Event Listener: runEmailSenderListener **Event Topic**: `appaili-notification-service-notification-email` When a notification is sent through the Email channel, this listener is triggered. It consumes messages from the `appaili-notification-service-notification-email` topic, parses the payload, and uses the dynamically configured email provider to send the notification. ### Kafka Event Listener: runPushSenderListener **Event Topic**: `appaili-notification-service-notification-push` When a notification is sent through the Push channel, this listener is triggered. It consumes messages from the `appaili-notification-service-notification-push` topic, parses the payload, and uses the dynamically configured push provider to send the notification. ### Kafka Event Listener: runSmsSenderListener **Event Topic**: `appaili-notification-service-notification-sms` When a notification is sent through the SMS channel, this listener is triggered. It consumes messages from the `appaili-notification-service-notification-sms` topic, parses the payload, and uses the dynamically configured SMS provider to send the notification. ### Kafka Event Listener: runaccountBannedListener **Event Topic**: `rtd1faifitapp-aicoach-service-dbevent-moderationrecord-created` When a notification is sent through the `rtd1faifitapp-aicoach-service-dbevent-moderationrecord-created` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (`ModerationNotificationView`). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runaccountBanReversedListener **Event Topic**: `rtd1faifitapp-aicoach-service-dbevent-moderationrecord-created` When a notification is sent through the `rtd1faifitapp-aicoach-service-dbevent-moderationrecord-created` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (`ModerationNotificationView`). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runchatSuspensionAppliedListener **Event Topic**: `rtd1faifitapp-aicoach-service-dbevent-moderationrecord-created` When a notification is sent through the `rtd1faifitapp-aicoach-service-dbevent-moderationrecord-created` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (`ModerationNotificationView`). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runemailVerificationListener **Event Topic**: `rtd1faifitapp-auth-service-dbevent-user-created` When a notification is sent through the `rtd1faifitapp-auth-service-dbevent-user-created` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runpasswordResetRequestedListener **Event Topic**: `rtd1faifitapp-auth-service-passwordreset-requested` When a notification is sent through the `rtd1faifitapp-auth-service-passwordreset-requested` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runsubscriptionActivatedListener **Event Topic**: `rtd1faifitapp-subscription-service-dbevent-subscription-updated` When a notification is sent through the `rtd1faifitapp-subscription-service-dbevent-subscription-updated` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (`SubscriptionNotificationView`). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runsubscriptionCancelledListener **Event Topic**: `rtd1faifitapp-subscription-service-subscription-cancelled` When a notification is sent through the `rtd1faifitapp-subscription-service-subscription-cancelled` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (`SubscriptionNotificationView`). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runemailVerificationListener **Event Topic**: `appaili-user-service-email-verification-start` When a notification is sent through the `appaili-user-service-email-verification-start` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runmobileVerificationListener **Event Topic**: `appaili-user-service-mobile-verification-start` When a notification is sent through the `appaili-user-service-mobile-verification-start` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runpasswordResetByEmailListener **Event Topic**: `appaili-user-service-password-reset-by-email-start` When a notification is sent through the `appaili-user-service-password-reset-by-email-start` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runpasswordResetByMobileListener **Event Topic**: `appaili-user-service-password-reset-by-mobile-start` When a notification is sent through the `appaili-user-service-password-reset-by-mobile-start` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runemail2FactorListener **Event Topic**: `appaili-user-service-email-2FA-start` When a notification is sent through the `appaili-user-service-email-2FA-start` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. ### Kafka Event Listener: runmobile2FactorListener **Event Topic**: `appaili-user-service-mobile-2FA-start` When a notification is sent through the `appaili-user-service-mobile-2FA-start` topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template (`[object Object]`). It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the `dataView` source is used (``). The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service. --- # LLM Documents --- *Generated by Mindbricks Genesis Engine*