# TutorHub Educational Platform - Complete Documentation > TutorHub is an educational platform connecting students with tutors for personalized learning experiences. Features include tutor profiles, course packs, scheduling, enrollments, and payment processing. This document contains the full documentation for all services in the TutorHub Educational Platform 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) - [TutorCatalog Service](#frontend-prompts-frontend-prompt-7-tutorcatalogservice) - [CourseScheduling Service](#frontend-prompts-frontend-prompt-8-courseschedulingservice) - [EnrollmentManagement Service](#frontend-prompts-frontend-prompt-9-enrollmentmanagementservice) - [EnrollmentManagement Service Enrollment Payment Flow](#frontend-prompts-frontend-prompt-10-enrollment-payment-flow) - [PlatformAdmin Service](#frontend-prompts-frontend-prompt-11-platformadminservice) - [Messaging Service](#frontend-prompts-frontend-prompt-12-messagingservice) - [Messaging Service Realtime Hubs](#frontend-prompts-frontend-prompt-13-messaging-realtimehubs) - [AgentHub Service](#frontend-prompts-frontend-prompt-14-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) - [applyAsTutor API](#auth-service-business-api-applyastutor-api-design) - [reviewTutorApplication API](#auth-service-business-api-reviewtutorapplication-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) ### TutorCatalog Service - [Service Design](#tutorcatalog-service-service-design) - [REST API Guide](#tutorcatalog-service-rest-api-guide) - [Event Guide](#tutorcatalog-service-event-guide) - **Data Objects** - [tutorProfile Design](#tutorcatalog-service-tutorprofile-design) - [coursePack Design](#tutorcatalog-service-coursepack-design) - [courseMaterial Design](#tutorcatalog-service-coursematerial-design) - [courseCategory Design](#tutorcatalog-service-coursecategory-design) - **Business APIs** - [createTutorProfile API](#tutorcatalog-service-business-api-createtutorprofile-api-design) - [updateTutorProfile API](#tutorcatalog-service-business-api-updatetutorprofile-api-design) - [getTutorProfile API](#tutorcatalog-service-business-api-gettutorprofile-api-design) - [listTutorProfiles API](#tutorcatalog-service-business-api-listtutorprofiles-api-design) - [createCoursePack API](#tutorcatalog-service-business-api-createcoursepack-api-design) - [updateCoursePack API](#tutorcatalog-service-business-api-updatecoursepack-api-design) - [deleteCoursePack API](#tutorcatalog-service-business-api-deletecoursepack-api-design) - [getCoursePack API](#tutorcatalog-service-business-api-getcoursepack-api-design) - [listCoursePacks API](#tutorcatalog-service-business-api-listcoursepacks-api-design) - [createCourseMaterial API](#tutorcatalog-service-business-api-createcoursematerial-api-design) - [updateCourseMaterial API](#tutorcatalog-service-business-api-updatecoursematerial-api-design) - [deleteCourseMaterial API](#tutorcatalog-service-business-api-deletecoursematerial-api-design) - [getCourseMaterial API](#tutorcatalog-service-business-api-getcoursematerial-api-design) - [listCourseMaterials API](#tutorcatalog-service-business-api-listcoursematerials-api-design) - [createCourseCategory API](#tutorcatalog-service-business-api-createcoursecategory-api-design) - [updateCourseCategory API](#tutorcatalog-service-business-api-updatecoursecategory-api-design) - [deleteCourseCategory API](#tutorcatalog-service-business-api-deletecoursecategory-api-design) - [getCourseCategory API](#tutorcatalog-service-business-api-getcoursecategory-api-design) - [listCourseCategories API](#tutorcatalog-service-business-api-listcoursecategories-api-design) - [onTutorApplicationReviewed API](#tutorcatalog-service-business-api-ontutorapplicationreviewed-api-design) - [Service Library](#tutorcatalog-service-service-library) ### CourseScheduling Service - [Service Design](#coursescheduling-service-service-design) - [REST API Guide](#coursescheduling-service-rest-api-guide) - [Event Guide](#coursescheduling-service-event-guide) - **Data Objects** - [availability Design](#coursescheduling-service-availability-design) - [lessonSlot Design](#coursescheduling-service-lessonslot-design) - [preliminaryMeeting Design](#coursescheduling-service-preliminarymeeting-design) - **Business APIs** - [createAvailability API](#coursescheduling-service-business-api-createavailability-api-design) - [updateAvailability API](#coursescheduling-service-business-api-updateavailability-api-design) - [deleteAvailability API](#coursescheduling-service-business-api-deleteavailability-api-design) - [getAvailability API](#coursescheduling-service-business-api-getavailability-api-design) - [listAvailabilities API](#coursescheduling-service-business-api-listavailabilities-api-design) - [createLessonSlot API](#coursescheduling-service-business-api-createlessonslot-api-design) - [updateLessonSlot API](#coursescheduling-service-business-api-updatelessonslot-api-design) - [deleteLessonSlot API](#coursescheduling-service-business-api-deletelessonslot-api-design) - [getLessonSlot API](#coursescheduling-service-business-api-getlessonslot-api-design) - [listLessonSlots API](#coursescheduling-service-business-api-listlessonslots-api-design) - [createPreliminaryMeeting API](#coursescheduling-service-business-api-createpreliminarymeeting-api-design) - [updatePreliminaryMeeting API](#coursescheduling-service-business-api-updatepreliminarymeeting-api-design) - [getPreliminaryMeeting API](#coursescheduling-service-business-api-getpreliminarymeeting-api-design) - [listPreliminaryMeetings API](#coursescheduling-service-business-api-listpreliminarymeetings-api-design) - [Service Library](#coursescheduling-service-service-library) ### EnrollmentManagement Service - [Service Design](#enrollmentmanagement-service-service-design) - [REST API Guide](#enrollmentmanagement-service-rest-api-guide) - [Event Guide](#enrollmentmanagement-service-event-guide) - **Data Objects** - [enrollment Design](#enrollmentmanagement-service-enrollment-design) - [refundRequest Design](#enrollmentmanagement-service-refundrequest-design) - [sys_enrollmentPayment Design](#enrollmentmanagement-service-sys-enrollmentpayment-design) - [sys_paymentCustomer Design](#enrollmentmanagement-service-sys-paymentcustomer-design) - [sys_paymentMethod Design](#enrollmentmanagement-service-sys-paymentmethod-design) - **Business APIs** - [createEnrollment API](#enrollmentmanagement-service-business-api-createenrollment-api-design) - [getEnrollment API](#enrollmentmanagement-service-business-api-getenrollment-api-design) - [listEnrollments API](#enrollmentmanagement-service-business-api-listenrollments-api-design) - [createRefundRequest API](#enrollmentmanagement-service-business-api-createrefundrequest-api-design) - [getRefundRequest API](#enrollmentmanagement-service-business-api-getrefundrequest-api-design) - [listRefundRequests API](#enrollmentmanagement-service-business-api-listrefundrequests-api-design) - [updateRefundRequest API](#enrollmentmanagement-service-business-api-updaterefundrequest-api-design) - [cancelEnrollment API](#enrollmentmanagement-service-business-api-cancelenrollment-api-design) - [adminRefundEnrollment API](#enrollmentmanagement-service-business-api-adminrefundenrollment-api-design) - [cascadeTutorBan API](#enrollmentmanagement-service-business-api-cascadetutorban-api-design) - [cascadeCourseRemoval API](#enrollmentmanagement-service-business-api-cascadecourseremoval-api-design) - [cleanupPendingEnrollments API](#enrollmentmanagement-service-business-api-cleanuppendingenrollments-api-design) - [checkEnrollmentCompletion API](#enrollmentmanagement-service-business-api-checkenrollmentcompletion-api-design) - [getEnrollmentPayment API](#enrollmentmanagement-service-business-api-getenrollmentpayment-api-design) - [listEnrollmentPayments API](#enrollmentmanagement-service-business-api-listenrollmentpayments-api-design) - [createEnrollmentPayment API](#enrollmentmanagement-service-business-api-createenrollmentpayment-api-design) - [updateEnrollmentPayment API](#enrollmentmanagement-service-business-api-updateenrollmentpayment-api-design) - [deleteEnrollmentPayment API](#enrollmentmanagement-service-business-api-deleteenrollmentpayment-api-design) - [getEnrollmentPaymentByOrderId API](#enrollmentmanagement-service-business-api-getenrollmentpaymentbyorderid-api-design) - [getEnrollmentPaymentByPaymentId API](#enrollmentmanagement-service-business-api-getenrollmentpaymentbypaymentid-api-design) - [startEnrollmentPayment API](#enrollmentmanagement-service-business-api-startenrollmentpayment-api-design) - [refreshEnrollmentPayment API](#enrollmentmanagement-service-business-api-refreshenrollmentpayment-api-design) - [callbackEnrollmentPayment API](#enrollmentmanagement-service-business-api-callbackenrollmentpayment-api-design) - [getPaymentCustomerByUserId API](#enrollmentmanagement-service-business-api-getpaymentcustomerbyuserid-api-design) - [listPaymentCustomers API](#enrollmentmanagement-service-business-api-listpaymentcustomers-api-design) - [listPaymentCustomerMethods API](#enrollmentmanagement-service-business-api-listpaymentcustomermethods-api-design) - [Service Library](#enrollmentmanagement-service-service-library) ### PlatformAdmin Service - [Service Design](#platformadmin-service-service-design) - [REST API Guide](#platformadmin-service-rest-api-guide) - [Event Guide](#platformadmin-service-event-guide) - **Data Objects** - [adminIssue Design](#platformadmin-service-adminissue-design) - [adminModerationAction Design](#platformadmin-service-adminmoderationaction-design) - [adminAnalyticsReport Design](#platformadmin-service-adminanalyticsreport-design) - **Business APIs** - [createAdminIssue API](#platformadmin-service-business-api-createadminissue-api-design) - [updateAdminIssue API](#platformadmin-service-business-api-updateadminissue-api-design) - [getAdminIssue API](#platformadmin-service-business-api-getadminissue-api-design) - [listAdminIssues API](#platformadmin-service-business-api-listadminissues-api-design) - [createAdminModerationAction API](#platformadmin-service-business-api-createadminmoderationaction-api-design) - [getAdminModerationAction API](#platformadmin-service-business-api-getadminmoderationaction-api-design) - [listAdminModerationActions API](#platformadmin-service-business-api-listadminmoderationactions-api-design) - [createAdminAnalyticsReport API](#platformadmin-service-business-api-createadminanalyticsreport-api-design) - [getAdminAnalyticsReport API](#platformadmin-service-business-api-getadminanalyticsreport-api-design) - [listAdminAnalyticsReports API](#platformadmin-service-business-api-listadminanalyticsreports-api-design) - [listMyIssues API](#platformadmin-service-business-api-listmyissues-api-design) ### Messaging Service - [Service Design](#messaging-service-service-design) - [REST API Guide](#messaging-service-rest-api-guide) - [Event Guide](#messaging-service-event-guide) - **Data Objects** - [conversation Design](#messaging-service-conversation-design) - [chatMessage Design](#messaging-service-chatmessage-design) - [chatModeration Design](#messaging-service-chatmoderation-design) - **Business APIs** - [createConversation API](#messaging-service-business-api-createconversation-api-design) - [getConversation API](#messaging-service-business-api-getconversation-api-design) - [listMyConversations API](#messaging-service-business-api-listmyconversations-api-design) - [sendSystemMessage API](#messaging-service-business-api-sendsystemmessage-api-design) - [listChatMessages API](#messaging-service-business-api-listchatmessages-api-design) - [getChatMessage API](#messaging-service-business-api-getchatmessage-api-design) - [deleteChatMessage API](#messaging-service-business-api-deletechatmessage-api-design) - [updateChatMessage API](#messaging-service-business-api-updatechatmessage-api-design) - **Realtime Hubs** - [chat Hub](#messaging-service-realtime-hubs-chat-hub-design) ### 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 ## TutorHub Educational Platform # TutorHub Educational Platform Version : 1.0.502 TutorHub is an educational platform connecting students with tutors for personalized learning experiences. Features include tutor profiles, course packs, scheduling, enrollments, and payment processing. ## How to Use Project Documents The `Tutorhub` 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://tutorhub.prw.mindbricks.com/auth-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/auth-api` | | **Production** | `https://tutorhub.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 `Tutorhub` 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 `TutorHub Educational Platform` 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 ### tutorCatalog Service **Description:** Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. **Documentation:** * [REST API Guide](/document/docs/tutorCatalog-service/rest-api-guide.html) * [Event Guide](/document/docs/tutorCatalog-service/event-guide.html) * [Service Design](/document/docs/tutorCatalog-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://tutorhub.prw.mindbricks.com/tutorcatalog-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/tutorcatalog-api` | | **Production** | `https://tutorhub.mindbricks.co/tutorcatalog-api` | ### courseScheduling Service **Description:** Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). **Documentation:** * [REST API Guide](/document/docs/courseScheduling-service/rest-api-guide.html) * [Event Guide](/document/docs/courseScheduling-service/event-guide.html) * [Service Design](/document/docs/courseScheduling-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://tutorhub.prw.mindbricks.com/coursescheduling-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/coursescheduling-api` | | **Production** | `https://tutorhub.mindbricks.co/coursescheduling-api` | ### enrollmentManagement Service **Description:** Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. **Documentation:** * [REST API Guide](/document/docs/enrollmentManagement-service/rest-api-guide.html) * [Event Guide](/document/docs/enrollmentManagement-service/event-guide.html) * [Service Design](/document/docs/enrollmentManagement-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api` | | **Production** | `https://tutorhub.mindbricks.co/enrollmentmanagement-api` | ### platformAdmin Service **Description:** No description provided. **Documentation:** * [REST API Guide](/document/docs/platformAdmin-service/rest-api-guide.html) * [Event Guide](/document/docs/platformAdmin-service/event-guide.html) * [Service Design](/document/docs/platformAdmin-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://tutorhub.prw.mindbricks.com/platformadmin-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/platformadmin-api` | | **Production** | `https://tutorhub.mindbricks.co/platformadmin-api` | ### messaging Service **Description:** Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. **Documentation:** * [REST API Guide](/document/docs/messaging-service/rest-api-guide.html) * [Event Guide](/document/docs/messaging-service/event-guide.html) * [Service Design](/document/docs/messaging-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://tutorhub.prw.mindbricks.com/messaging-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/messaging-api` | | **Production** | `https://tutorhub.mindbricks.co/messaging-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://tutorhub.prw.mindbricks.com/agenthub-api` | | **Staging** | `https://tutorhub-stage.mindbricks.co/agenthub-api` | | **Production** | `https://tutorhub.mindbricks.co/agenthub-api` | ## Connect via MCP (Model Context Protocol) All backend services in the `Tutorhub` 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://tutorhub.prw.mindbricks.com/mcpbff-api/mcp` | `https://tutorhub.prw.mindbricks.com/mcpbff-api/mcp/sse` | | **Staging** | `https://tutorhub-stage.mindbricks.co/mcpbff-api/mcp` | `https://tutorhub-stage.mindbricks.co/mcpbff-api/mcp/sse` | | **Production** | `https://tutorhub.mindbricks.co/mcpbff-api/mcp` | `https://tutorhub.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": { "tutorhub": { "url": "https://tutorhub.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": { "tutorhub": { "url": "https://tutorhub.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 `TutorHub Educational Platform` 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 # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Project Introduction & Setup** This is the introductory document for the **tutorhub** 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 TutorHub is an educational platform connecting students with tutors for personalized learning experiences. Features include tutor profiles, course packs, scheduling, enrollments, and payment processing. ## Project Services Overview The project has **1 auth service**, **1 notification service**, **1 BFF service**, and **6 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 | tutorCatalog | Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. | `/tutorCatalog-api` | | 3 | courseScheduling | Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). | `/courseScheduling-api` | | 4 | enrollmentManagement | Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. | `/enrollmentManagement-api` | | 5 | platformAdmin | platformAdmin | `/platformAdmin-api` | | 6 | messaging | Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. | `/messaging-api` | | 7 | 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://tutorhub.prw.mindbricks.com` * **Staging:** `https://tutorhub-stage.mindbricks.co` * **Production:** `https://tutorhub.mindbricks.co` For the auth service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.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) - TutorCatalog Service Pages - CourseScheduling Service Pages - EnrollmentManagement Service Pages - PlatformAdmin Service Pages - Messaging 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 # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Authentication Management** This document covers the authentication features of the **tutorhub** 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://tutorhub.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://tutorhub.prw.mindbricks.com` | | stage | `https://tutorhub-stage.mindbricks.co` | | prod | `https://tutorhub.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 10 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"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | **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. **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **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", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", }, 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Verification Management** This document is a part of a REST API guide for the tutorhub 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 6 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://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.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 # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - Profile Management** This document is a part of a REST API guide for the tutorhub 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 6 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://tutorhub.prw.mindbricks.com` * **Staging:** `https://tutorhub-stage.mindbricks.co` * **Production:** `https://tutorhub.mindbricks.co` For the auth service, service urls are as follows: * **Preview:** `https://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **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 **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **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", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - User Management** This document is the 2nd part of a REST API guide for the tutorhub 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://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.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 tutorhub 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 3 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` **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 } }); ``` **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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 1 optional filter parameter 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` **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 } }); ``` **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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 10 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"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | **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 **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **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", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", }, 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **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 **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **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", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - MCP BFF Integration** This document is a part of a REST API guide for the tutorhub 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 Tutorhub 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://tutorhub.prw.mindbricks.com/mcpbff-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/mcpbff-api` * **Production:** `https://tutorhub.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 `tutorhub_`). ```js const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers }); // ["tutorhub_products", "tutorhub_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 `tutorhub_` 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 | | `tutorCatalog` | Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. | | `courseScheduling` | Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). | | `enrollmentManagement` | Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. | | `platformAdmin` | | | `messaging` | Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. | | `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://tutorhub.prw.mindbricks.com/mcpbff-api/mcp` | | **Staging** | `https://tutorhub-stage.mindbricks.co/mcpbff-api/mcp` | | **Production** | `https://tutorhub.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": { "tutorhub": { "url": "https://tutorhub.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } } ``` **Claude Desktop** (`claude_desktop_config.json`): ```json { "mcpServers": { "tutorhub": { "url": "https://tutorhub.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.** --- ## TutorCatalog Service # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - TutorCatalog Service** This document is a part of a REST API guide for the tutorhub 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 tutorCatalog ## Service Access TutorCatalog service management is handled through service specific base urls. TutorCatalog 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 tutorCatalog service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/tutorcatalog-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/tutorcatalog-api` * **Production:** `https://tutorhub.mindbricks.co/tutorcatalog-api` ## Scope **TutorCatalog Service Description** Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. TutorCatalog service provides apis and business logic for following data objects in tutorhub 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. **`tutorProfile` Data Object**: Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. **`coursePack` Data Object**: Publicly listed course pack/structured course offered by a tutor. **`courseMaterial` Data Object**: Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. **`courseCategory` Data Object**: Represents a course subject/category; used for filtering and navigation. Admin-maintained. ## TutorCatalog Service Frontend Description By The Backend Architect - Tutor profiles and courses are public and discoverable for all users. - Authenticated users can see more details and interact (enroll, etc.) via other services (not here). - Tutors can CRUD their own profile, courses, and materials. - Public lists/searches available for filtering by category, subject, profile, strict/flexible scheduling, and published status. - Materials (files, links) visible only to enrolled students and the owning tutor. - Categories shown automatically with all courses for navigation/filtering. - Admin actions handled elsewhere; this service focuses on public and owner-level CRUD. ## 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" } ``` ## TutorProfile Data Object Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. ### TutorProfile Data Object Frontend Description By The Backend Architect ## Tutor Approval Workflow ### Approval Status - Every tutorProfile has a `profileStatus` field (enum): - **pending**: Profile submitted by the tutor and awaiting admin review. - **approved**: Profile has been reviewed and accepted by an admin. Tutor is fully visible in public listings, and can publish course packs. - **rejected**: Profile was rejected by an admin. Tutor must review reasons (optional admin comment/notification) and resubmit. ### Required Actions - **Tutor** (when profile is pending or rejected): - Cannot publish any courses or be shown in public tutor/course pack listings. - Sees a prominent banner/message in their dashboard noting: "Your profile is pending approval." or "Your profile was rejected. Please review feedback and resubmit." - Can submit profile edits for resubmission if status is 'rejected' (ideally guided by admin feedback). - **Admin:** - Sees all tutor profiles in a moderation/approval dashboard with filtering by status. - Must use the `updateTutorProfile` API/route to set 'approved' or 'rejected'. - When approving: updates profileStatus = approved. Tutor becomes publicly visible and can create/publish course packs. - When rejecting: updates profileStatus = rejected (optionally includes rejection reason). Tutor receives visible reason/cue to edit/resubmit. ### Tutor-Facing UX Cues - When `profileStatus=pending`: Dashboard disables publish/listing actions, overlays banner like "Your profile is under review by our admins. Approval may take 1-2 business days." - When `profileStatus=rejected`: Red banner with reason(s) from admin, clear edit/resubmit call-to-action, disables publish/listing actions until resubmission is accepted. - When `profileStatus=approved`: All usual actions enabled. Profile listed publicly, can publish courses. ### Admin-Facing UI Guidance - Approval dashboard should provide filters for status, easy action buttons to 'Approve'/'Reject' (triggering `updateTutorProfile`). - On reject, prompt for reason. On approve, optional (confirmation only). ### User Stories - **As a Tutor:** - I want to be clearly informed if my profile is under review or rejected, so I can understand what's next. - I want to see actionable messages if rejected, with admin feedback, and a way to edit and resubmit. - I want assurance that my profile won't be public or allow course creation until approved. - If my profile is approved, I want to immediately be able to create/publish courses and appear in searches. - **As an Admin:** - I need to review pending tutor profiles and approve or reject with a provided reason. - After rejection, I want tutors to see my feedback and be able to resubmit. - I want an efficient dashboard to filter/search pending tutors and update status with minimal friction. - **Edge Cases:** - Tutor repeatedly rejected => each rejection shows latest reason, and only can resubmit after another edit. - If tutor edits their profile after approval, system may revert status to 'pending' (if desired—should be clarified per business rule). - Tutor attempts course publishing or visibility actions while pending/rejected: Block with clear explanation. #### User Stories (continued) - **US45 (Tutor — Profile Approval):** - *As a tutor, I want my profile to be reviewed and approved by the admin before it becomes public so that students can trust the tutors on the platform.* - **US46 (Admin — Approve/Reject Tutor Profiles):** - *As an admin, I want to review and approve or reject tutor profiles so that only qualified tutors can offer courses on the platform.* - **US47 (System/Tutor — Course Pack Restriction):** - *As the platform, I want to allow only approved tutors to create course packs so that unverified tutors cannot publish courses.* --- #### Bullet Summary: User Stories - **Tutor:** - See clear status (pending/approved/rejected) on dashboard - Receive rejection reason and actionable guidance - Blocked from course publishing/listing unless approved - Able to resubmit after rejection - **Admin:** - Filter and view tutor profiles by status - Approve/reject profiles via updateTutorProfile UI, with optional reason on reject - Provide rejection feedback - Workflow supports multiple reviews/resubmissions and edge cases ### TutorProfile Data Object Properties TutorProfile 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 | |----------|------|---------|----------|--------|-------------| | `tutorId` | ID | false | Yes | No | - | | `certifications` | String | true | No | No | Tutor's certifications (list of certificates, degrees, etc.). | | `experience` | Text | false | No | No | Brief experience summary or bio. | | `subjects` | String | true | No | No | Areas of expertise/subjects offered for teaching. | | `bio` | Text | false | No | No | Optional full-length bio/description. | | `profilePhoto` | String | false | No | No | Public profile photo URL (may be external or uploaded). | | `profileStatus` | Enum | false | Yes | No | - | | `displayName` | String | false | No | No | Tutor's display name, copied from auth user fullname at profile creation. | * 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. ### Array Properties `certifications` `subjects` Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed. ### 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. - **profileStatus**: [pending, approved, rejected] ### Relation Properties `tutorId` 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. - **tutorId**: 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 `tutorId` `profileStatus` 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. - **tutorId**: ID has a filter named `tutorId` - **profileStatus**: Enum has a filter named `profileStatus` ## CoursePack Data Object Publicly listed course pack/structured course offered by a tutor. ### CoursePack Data Object Properties CoursePack 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 | |----------|------|---------|----------|--------|-------------| | `tutorProfileId` | ID | | Yes | No | - | | `title` | String | false | Yes | No | - | | `description` | Text | false | No | No | - | | `price` | Double | false | Yes | No | - | | `category` | String | false | Yes | No | - | | `schedulingType` | Enum | false | Yes | No | - | | `minWeeklyClasses` | Integer | false | No | No | - | | `preliminaryMeetingRequired` | Boolean | false | Yes | No | - | | `isPublished` | Boolean | false | Yes | No | - | | `maxDailyLessons` | Integer | false | No | No | - | | `requiredClassesCount` | Integer | false | No | No | - | | `moderationStatus` | Enum | false | No | No | Content moderation status. | | `moderationNote` | String | false | No | No | Admin note for flagged/removed course packs. | | `maxPeriodValue` | Integer | false | No | No | Maximum time period value for strict scheduling (e.g. 3 for 3 months) | | `maxPeriodUnit` | Enum | false | No | No | Time unit for maxPeriodValue in strict scheduling | * 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. - **schedulingType**: [flexible, strict] - **moderationStatus**: [approved, flagged, removed] - **maxPeriodUnit**: [weeks, months] ### Relation Properties `tutorProfileId` `category` 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. - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **category**: String Relation to `courseCategory`.name The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `tutorProfileId` `title` `category` `schedulingType` `isPublished` `moderationStatus` 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. - **tutorProfileId**: ID has a filter named `tutorProfileId` - **title**: String has a filter named `courseTitle` - **category**: String has a filter named `category` - **schedulingType**: Enum has a filter named `scheduling` - **isPublished**: Boolean has a filter named `published` - **moderationStatus**: Enum has a filter named `moderationStatus` ## CourseMaterial Data Object Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. ### CourseMaterial Data Object Frontend Description By The Backend Architect - Created and managed by course's tutor. - Only visible to students enrolled in the pack and the tutor (not public). - Often accessed post-enrollment via BFF/data view—but single API allows secure download/listing for eligible users. ### CourseMaterial Data Object Properties CourseMaterial 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 | |----------|------|---------|----------|--------|-------------| | `coursePackId` | ID | false | Yes | No | FK to coursePack. | | `fileUrl` | String | false | Yes | No | URL for file/video/document. For downloads or video links (protected). | | `fileType` | Enum | false | Yes | No | Type: file, video, document, externalLink. | | `title` | String | false | Yes | No | Material title (unique per pack). | | `description` | Text | false | No | No | Additional details about the material resource. | | `linkUrl` | String | false | No | No | Optional URL for external resource (if fileType = externalLink). | * 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. - **fileType**: [file, video, document, externalLink] ### Relation Properties `coursePackId` 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. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### Filter Properties `fileType` 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. - **fileType**: Enum has a filter named `type` ## CourseCategory Data Object Represents a course subject/category; used for filtering and navigation. Admin-maintained. ### CourseCategory Data Object Frontend Description By The Backend Architect - Managed by admins for site-wide course organization; visible to all users. - Used as label/tag on coursePack objects for filtering and browsing. - Categories displayed with all courses on public site. Only admins can create/edit/delete categories. ### CourseCategory Data Object Properties CourseCategory 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 | |----------|------|---------|----------|--------|-------------| | `name` | String | false | Yes | No | Unique category/subject name. | | `description` | Text | false | No | No | Category description. | | `icon` | String | false | No | No | Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) | * 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 `name` 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. - **name**: String has a filter named `name` ## 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. ### TutorProfile Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createTutorProfile` | `/v1/tutorprofiles` | Auto | | Update | `updateTutorProfile` | `/v1/tutorprofiles/:tutorProfileId` | Yes | | Delete | _none_ | - | Auto | | Get | `getTutorProfile` | `/v1/tutorprofiles/:tutorProfileId` | Yes | | List | `listTutorProfiles` | `/v1/tutorprofiles` | Auto | ### CoursePack Default APIs **Display Label Property:** `title` — 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 | `createCoursePack` | `/v1/coursepacks` | Yes | | Update | `updateCoursePack` | `/v1/coursepacks/:coursePackId` | Yes | | Delete | `deleteCoursePack` | `/v1/coursepacks/:coursePackId` | Yes | | Get | `getCoursePack` | `/v1/coursepacks/:coursePackId` | Yes | | List | `listCoursePacks` | `/v1/coursepacks` | Auto | ### CourseMaterial Default APIs **Display Label Property:** `title` — 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 | `createCourseMaterial` | `/v1/coursematerials` | Yes | | Update | `updateCourseMaterial` | `/v1/coursematerials/:courseMaterialId` | Yes | | Delete | `deleteCourseMaterial` | `/v1/coursematerials/:courseMaterialId` | Yes | | Get | `getCourseMaterial` | `/v1/coursematerials/:courseMaterialId` | Yes | | List | `listCourseMaterials` | `/v1/coursematerials` | Yes | ### CourseCategory Default APIs **Display Label Property:** `name` — 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 | `createCourseCategory` | `/v1/coursecategories` | Yes | | Update | `updateCourseCategory` | `/v1/coursecategories/:courseCategoryId` | Yes | | Delete | `deleteCourseCategory` | `/v1/coursecategories/:courseCategoryId` | Yes | | Get | `getCourseCategory` | `/v1/coursecategories/:name` | Yes | | List | `listCourseCategories` | `/v1/coursecategories` | 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 ### `Create Tutorprofile` API **Rest Route** The `createTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles` **Rest Request Parameters** The `createTutorProfile` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | bio | Text | false | request.body?.["bio"] | | experience | Text | false | request.body?.["experience"] | | profileStatus | String | false | request.body?.["profileStatus"] | | certifications | String | false | request.body?.["certifications"] | | subjects | String | false | request.body?.["subjects"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | displayName | String | false | request.body?.["displayName"] | **tutorId** : ID of the auth user who is becoming a tutor **bio** : Tutor's biography **experience** : Tutor's experience/qualifications **profileStatus** : Approval status - should be 'approved' when created from auth **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **subjects** : Areas of expertise/subjects offered for teaching. **profilePhoto** : Public profile photo URL (may be external or uploaded). **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/tutorprofiles** ```js axios({ method: 'POST', url: '/v1/tutorprofiles', data: { tutorId:"ID", bio:"Text", experience:"Text", profileStatus:"String", certifications:"String", subjects:"String", profilePhoto:"String", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Tutorprofile` API **[Default update API]** — This is the designated default `update` API for the `tutorProfile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates their own profile. Only owner tutor or admin can update. **Rest Route** The `updateTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` **Rest Request Parameters** The `updateTutorProfile` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | | tutorId | ID | false | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | false | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | **tutorProfileId** : This id paremeter is used to select the required data object that will be updated **tutorId** : **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **experience** : Brief experience summary or bio. **subjects** : Areas of expertise/subjects offered for teaching. **bio** : Optional full-length bio/description. **profilePhoto** : Public profile photo URL (may be external or uploaded). **profileStatus** : **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/tutorprofiles/:tutorProfileId** ```js axios({ method: 'PATCH', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Tutorprofile` API **[Default get API]** — This is the designated default `get` API for the `tutorProfile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly get a tutor profile by ID. No login required. **Rest Route** The `getTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` **Rest Request Parameters** The `getTutorProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | **tutorProfileId** : 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/tutorprofiles/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Tutorprofiles` API **Rest Route** The `listTutorProfiles` API REST controller can be triggered via the following route: `/v1/tutorprofiles` **Rest Request Parameters** The `listTutorProfiles` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/tutorprofiles** ```js axios({ method: 'GET', url: '/v1/tutorprofiles', 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": "tutorProfiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "tutorProfiles": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursepack` API **[Default create API]** — This is the designated default `create` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor creates a new course offering. Only accessible to tutors (or admin, for moderation). **Rest Route** The `createCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks` **Rest Request Parameters** The `createCoursePack` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | true | request.body?.["price"] | | category | String | true | request.body?.["category"] | | schedulingType | Enum | true | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | true | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | true | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | **tutorProfileId** : **title** : **description** : **price** : **category** : **schedulingType** : **minWeeklyClasses** : **preliminaryMeetingRequired** : **isPublished** : **maxDailyLessons** : **requiredClassesCount** : **moderationNote** : Admin note for flagged/removed course packs. **maxPeriodValue** : Maximum time period value for strict scheduling (e.g. 3 for 3 months) **maxPeriodUnit** : Time unit for maxPeriodValue in strict scheduling **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursepacks** ```js axios({ method: 'POST', url: '/v1/coursepacks', data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursepack` API **[Default update API]** — This is the designated default `update` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates their course pack. Only owner tutor or admin can update. Ownership is verified via tutorProfile and user session. **Rest Route** The `updateCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `updateCoursePack` api has got 16 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | false | request.body?.["price"] | | category | String | false | request.body?.["category"] | | schedulingType | Enum | false | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | false | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | false | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationStatus | Enum | false | request.body?.["moderationStatus"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | **coursePackId** : This id paremeter is used to select the required data object that will be updated **tutorProfileId** : **title** : **description** : **price** : **category** : **schedulingType** : **minWeeklyClasses** : **preliminaryMeetingRequired** : **isPublished** : **maxDailyLessons** : **requiredClassesCount** : **moderationStatus** : Content moderation status. **moderationNote** : Admin note for flagged/removed course packs. **maxPeriodValue** : Maximum time period value for strict scheduling (e.g. 3 for 3 months) **maxPeriodUnit** : Time unit for maxPeriodValue in strict scheduling **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursepacks/:coursePackId** ```js axios({ method: 'PATCH', url: `/v1/coursepacks/${coursePackId}`, data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationStatus:"Enum", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursepack` API **[Default delete API]** — This is the designated default `delete` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes their course pack. Only owner tutor or admin can delete. Tutors are blocked if active enrollments exist. Admin can force-delete with a reason, which triggers pro-rata refunds and student notifications. **API Frontend Description By The Backend Architect** Tutors cannot delete a course with active enrollments — they should unpublish instead. Admin can force-delete with a mandatory reason; this triggers automatic pro-rata refunds and email notifications to affected students. **Rest Route** The `deleteCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `deleteCoursePack` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | removalReason | String | | request.body?.["removalReason"] | **coursePackId** : This id paremeter is used to select the required data object that will be deleted **removalReason** : Required when admin deletes a course with active enrollments. Reason is sent to affected students via email. **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/coursepacks/:coursePackId** ```js axios({ method: 'DELETE', url: `/v1/coursepacks/${coursePackId}`, data: { removalReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursepack` API **[Default get API]** — This is the designated default `get` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly get a course pack by ID. No login required. **Rest Route** The `getCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `getCoursePack` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | **coursePackId** : 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/coursepacks/:coursePackId** ```js axios({ method: 'GET', url: `/v1/coursepacks/${coursePackId}`, 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": "coursePack", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coursePack": { "tutorProfile": { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, "isActive": true } } ``` ### `List Coursepacks` API **Rest Route** The `listCoursePacks` API REST controller can be triggered via the following route: `/v1/coursepacks` **Rest Request Parameters** The `listCoursePacks` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursepacks** ```js axios({ method: 'GET', url: '/v1/coursepacks', 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": "coursePacks", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coursePacks": [ { "tutorProfile": [ { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursematerial` API **[Default create API]** — This is the designated default `create` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor uploads a material to a course pack they own. Only tutor or admin can create. **Rest Route** The `createCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials` **Rest Request Parameters** The `createCourseMaterial` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | fileUrl | String | true | request.body?.["fileUrl"] | | fileType | Enum | true | request.body?.["fileType"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | **coursePackId** : FK to coursePack. **fileUrl** : URL for file/video/document. For downloads or video links (protected). **fileType** : Type: file, video, document, externalLink. **title** : Material title (unique per pack). **description** : Additional details about the material resource. **linkUrl** : Optional URL for external resource (if fileType = externalLink). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursematerials** ```js axios({ method: 'POST', url: '/v1/coursematerials', data: { coursePackId:"ID", fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursematerial` API **[Default update API]** — This is the designated default `update` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates course material. Only course's tutor or admin can update. **Rest Route** The `updateCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `updateCourseMaterial` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | | fileUrl | String | false | request.body?.["fileUrl"] | | fileType | Enum | false | request.body?.["fileType"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | **courseMaterialId** : This id paremeter is used to select the required data object that will be updated **fileUrl** : URL for file/video/document. For downloads or video links (protected). **fileType** : Type: file, video, document, externalLink. **title** : Material title (unique per pack). **description** : Additional details about the material resource. **linkUrl** : Optional URL for external resource (if fileType = externalLink). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'PATCH', url: `/v1/coursematerials/${courseMaterialId}`, data: { fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursematerial` API **[Default delete API]** — This is the designated default `delete` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes course material. Only course's tutor or admin can delete. **Rest Route** The `deleteCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `deleteCourseMaterial` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | **courseMaterialId** : 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/coursematerials/:courseMaterialId** ```js axios({ method: 'DELETE', url: `/v1/coursematerials/${courseMaterialId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursematerial` API **[Default get API]** — This is the designated default `get` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get course material. Only accessible by tutor owner or enrolled student or admin. **Rest Route** The `getCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `getCourseMaterial` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | **courseMaterialId** : 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/coursematerials/:courseMaterialId** ```js axios({ method: 'GET', url: `/v1/coursematerials/${courseMaterialId}`, 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": "courseMaterial", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` ### `List Coursematerials` API **[Default list API]** — This is the designated default `list` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List course materials for a coursePack. Only accessible to enrolled students, tutor owner, or admin. **Rest Route** The `listCourseMaterials` API REST controller can be triggered via the following route: `/v1/coursematerials` **Rest Request Parameters** The `listCourseMaterials` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursematerials** ```js axios({ method: 'GET', url: '/v1/coursematerials', 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": "courseMaterials", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseMaterials": [ { "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursecategory` API **[Default create API]** — This is the designated default `create` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin creates new course category/subject tag. **Rest Route** The `createCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories` **Rest Request Parameters** The `createCourseCategory` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | **name** : Unique category/subject name. **description** : Category description. **icon** : Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursecategories** ```js axios({ method: 'POST', url: '/v1/coursecategories', data: { name:"String", description:"Text", icon:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursecategory` API **[Default update API]** — This is the designated default `update` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin updates course category/subject tag. **Rest Route** The `updateCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` **Rest Request Parameters** The `updateCourseCategory` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | | name | String | false | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | **courseCategoryId** : This id paremeter is used to select the required data object that will be updated **name** : Unique category/subject name. **description** : Category description. **icon** : Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursecategories/:courseCategoryId** ```js axios({ method: 'PATCH', url: `/v1/coursecategories/${courseCategoryId}`, data: { name:"String", description:"Text", icon:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursecategory` API **[Default delete API]** — This is the designated default `delete` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin deletes a course category/subject tag. Only admin allowed. **Rest Route** The `deleteCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` **Rest Request Parameters** The `deleteCourseCategory` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | **courseCategoryId** : 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/coursecategories/:courseCategoryId** ```js axios({ method: 'DELETE', url: `/v1/coursecategories/${courseCategoryId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursecategory` API **[Default get API]** — This is the designated default `get` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly fetch a course category/subject by name. No login required. **Rest Route** The `getCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:name` **Rest Request Parameters** The `getCourseCategory` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.params?.["name"] | **name** : Unique category/subject name.. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursecategories/:name** ```js axios({ method: 'GET', url: `/v1/coursecategories/${name}`, 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": "courseCategory", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseCategory": { "isActive": true } } ``` ### `List Coursecategories` API **[Default list API]** — This is the designated default `list` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly list all course categories/subjects for navigation, filtering, and display. No login required. **Rest Route** The `listCourseCategories` API REST controller can be triggered via the following route: `/v1/coursecategories` **Rest Request Parameters** The `listCourseCategories` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursecategories** ```js axios({ method: 'GET', url: '/v1/coursecategories', 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": "courseCategories", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseCategories": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `On Tutorapplicationreviewed` API **API Frontend Description By The Backend Architect** Kafka event handler that creates tutor profile when auth service approves a tutor application. Listens to tutorhub-auth-service-tutorapplication-reviewed topic. **Rest Route** The `onTutorApplicationReviewed` API REST controller can be triggered via the following route: `/v1/ontutorapplicationreviewed` **Rest Request Parameters** The `onTutorApplicationReviewed` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | true | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | **tutorId** : **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **experience** : Brief experience summary or bio. **subjects** : Areas of expertise/subjects offered for teaching. **bio** : Optional full-length bio/description. **profilePhoto** : Public profile photo URL (may be external or uploaded). **profileStatus** : **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/ontutorapplicationreviewed** ```js axios({ method: 'POST', url: '/v1/ontutorapplicationreviewed', data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## CourseScheduling Service # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - CourseScheduling Service** This document is a part of a REST API guide for the tutorhub 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 courseScheduling ## Service Access CourseScheduling service management is handled through service specific base urls. CourseScheduling 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 courseScheduling service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/coursescheduling-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/coursescheduling-api` * **Production:** `https://tutorhub.mindbricks.co/coursescheduling-api` ## Scope **CourseScheduling Service Description** Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). CourseScheduling service provides apis and business logic for following data objects in tutorhub 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. **`availability` Data Object**: Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. **`lessonSlot` Data Object**: **`preliminaryMeeting` Data Object**: Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. ## CourseScheduling Service Frontend Description By The Backend Architect This service manages tutor lesson slot scheduling, preliminary screening meetings, and weekly availabilities for tutors. Schedule data is privacy-controlled: only tutors (for their own slots), enrolled students (for their course slots), and admins can access relevant entries. Public endpoints are not present; all APIs require authentication and membership validation. Lesson slot status changes are strictly regulated (ownership and state transitions checked). Availability can only be set/modified by the tutor or admin. ## 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" } ``` ## Availability Data Object Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. ### Availability Data Object Frontend Description By The Backend Architect Represents a recurring (or one-off) time window when the tutor is available for lessons. Only the owning tutor or admins may create or update these records. Frontend should provide a day-of-week picker and HH:mm input, plus a toggle for recurrence. ### Availability Data Object Properties Availability 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 | |----------|------|---------|----------|--------|-------------| | `tutorProfileId` | ID | false | Yes | No | FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. | | `dayOfWeek` | Enum | false | Yes | No | Day of week: sunday-saturday. | | `startTime` | String | false | Yes | No | Start time of window (HH:mm, 24h). | | `endTime` | String | false | Yes | No | End time of window (HH:mm, 24h). | | `isRecurring` | Boolean | false | Yes | No | If true, this slot recurs weekly. | | `specificDate` | Date | false | No | No | Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. | | `teachingMode` | 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. - **dayOfWeek**: [sunday, monday, tuesday, wednesday, thursday, friday, saturday] - **teachingMode**: [online, faceToFace, both] ### Relation Properties `tutorProfileId` 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. - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### Filter Properties `teachingMode` 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. - **teachingMode**: Enum has a filter named `teachingMode` ## LessonSlot Data Object ### LessonSlot Data Object Properties LessonSlot 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 | |----------|------|---------|----------|--------|-------------| | `coursePackId` | ID | false | Yes | No | FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. | | `studentId` | ID | false | No | No | FK to auth:user (student). Set on booking. Nullable when open (free). | | `scheduledDate` | Date | false | Yes | No | Date for the lesson slot (yyyy-mm-dd). | | `scheduledTime` | String | false | Yes | No | Start time of lesson (HH:mm 24h). | | `status` | Enum | false | Yes | No | State of lesson slot (free, booked, completed, canceled). | | `locationType` | Enum | false | No | No | - | | `locationDetails` | String | false | No | No | Optional: Location address/details; editable after booking by either party. | | `sessionMode` | Enum | false | Yes | No | Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. | | `meetLink` | String | false | No | No | Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. | * 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**: [free, booked, completed, canceled] - **locationType**: [online, studentHome, tutorHome, other] - **sessionMode**: [online, faceToFace] ### Relation Properties `coursePackId` `studentId` 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. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `coursePackId` `studentId` `status` `sessionMode` 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. - **coursePackId**: ID has a filter named `coursePackId` - **studentId**: ID has a filter named `studentId` - **status**: Enum has a filter named `status` - **sessionMode**: Enum has a filter named `sessionMode` ## PreliminaryMeeting Data Object Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. ### PreliminaryMeeting Data Object Frontend Description By The Backend Architect Represents a student's request for a screening with a tutor for an advanced course. Only active if the related coursePack has preliminaryMeetingRequired true. Student can request; tutor can schedule/approve/reject. Both parties and admins can view. Tutor may leave comments/notes. Each student-coursePack pair is unique. ### PreliminaryMeeting Data Object Properties PreliminaryMeeting 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 | |----------|------|---------|----------|--------|-------------| | `coursePackId` | ID | false | Yes | No | FK to tutorCatalog:coursePack (the advanced course) | | `studentId` | ID | false | Yes | No | FK to auth:user (student who requested). | | `scheduledDatetime` | Date | false | No | No | Datetime for screening meeting; may be null until both parties agree. | | `tutorDecision` | Enum | false | Yes | No | - | | `comments` | String | false | No | No | Optional field for tutor to provide comments/notes about screening result. | | `meetingLink` | String | false | No | No | Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. | * 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. - **tutorDecision**: [pending, approved, rejected] ### Relation Properties `coursePackId` `studentId` 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. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ## 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. ### Availability Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAvailability` | `/v1/availabilities` | Yes | | Update | `updateAvailability` | `/v1/availabilities/:availabilityId` | Yes | | Delete | `deleteAvailability` | `/v1/availabilities/:availabilityId` | Yes | | Get | `getAvailability` | `/v1/availabilities/:availabilityId` | Yes | | List | `listAvailabilities` | `/v1/listavailabilities/:tutorProfileId` | Auto | ### LessonSlot Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createLessonSlot` | `/v1/lessonslots` | Auto | | Update | `updateLessonSlot` | `/v1/lessonslots/:lessonSlotId` | Yes | | Delete | `deleteLessonSlot` | `/v1/lessonslots/:lessonSlotId` | Yes | | Get | `getLessonSlot` | `/v1/lessonslots/:lessonSlotId` | Auto | | List | `listLessonSlots` | `/v1/lessonslots` | Auto | ### PreliminaryMeeting Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createPreliminaryMeeting` | `/v1/preliminarymeetings` | Yes | | Update | `updatePreliminaryMeeting` | `/v1/preliminarymeetings/:preliminaryMeetingId` | Yes | | Delete | _none_ | - | Auto | | Get | `getPreliminaryMeeting` | `/v1/preliminarymeetings/:preliminaryMeetingId` | Yes | | List | `listPreliminaryMeetings` | `/v1/preliminarymeetings` | 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 ### `Create Availability` API **[Default create API]** — This is the designated default `create` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor creates available time window for teaching. Only owner tutor or admin. **Rest Route** The `createAvailability` API REST controller can be triggered via the following route: `/v1/availabilities` **Rest Request Parameters** The `createAvailability` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | dayOfWeek | Enum | true | request.body?.["dayOfWeek"] | | startTime | String | true | request.body?.["startTime"] | | endTime | String | true | request.body?.["endTime"] | | isRecurring | Boolean | true | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | true | request.body?.["teachingMode"] | **tutorProfileId** : FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. **dayOfWeek** : Day of week: sunday-saturday. **startTime** : Start time of window (HH:mm, 24h). **endTime** : End time of window (HH:mm, 24h). **isRecurring** : If true, this slot recurs weekly. **specificDate** : Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. **teachingMode** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/availabilities** ```js axios({ method: 'POST', url: '/v1/availabilities', data: { tutorProfileId:"ID", dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Availability` API **[Default update API]** — This is the designated default `update` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates an availability record (only own, or admin). **Rest Route** The `updateAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `updateAvailability` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | | dayOfWeek | Enum | false | request.body?.["dayOfWeek"] | | startTime | String | false | request.body?.["startTime"] | | endTime | String | false | request.body?.["endTime"] | | isRecurring | Boolean | false | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | false | request.body?.["teachingMode"] | **availabilityId** : This id paremeter is used to select the required data object that will be updated **dayOfWeek** : Day of week: sunday-saturday. **startTime** : Start time of window (HH:mm, 24h). **endTime** : End time of window (HH:mm, 24h). **isRecurring** : If true, this slot recurs weekly. **specificDate** : Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. **teachingMode** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/availabilities/:availabilityId** ```js axios({ method: 'PATCH', url: `/v1/availabilities/${availabilityId}`, data: { dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Availability` API **[Default delete API]** — This is the designated default `delete` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes an availability record (only own, or admin). **Rest Route** The `deleteAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `deleteAvailability` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | **availabilityId** : 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/availabilities/:availabilityId** ```js axios({ method: 'DELETE', url: `/v1/availabilities/${availabilityId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Availability` API **[Default get API]** — This is the designated default `get` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one availability by id (tutor/owner or admin only). **Rest Route** The `getAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `getAvailability` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | **availabilityId** : 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/availabilities/:availabilityId** ```js axios({ method: 'GET', url: `/v1/availabilities/${availabilityId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Availabilities` API **Rest Route** The `listAvailabilities` API REST controller can be triggered via the following route: `/v1/listavailabilities/:tutorProfileId` **Rest Request Parameters** The `listAvailabilities` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | **tutorProfileId** : FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit.. The parameter is used to query data. **Filter Parameters** The `listAvailabilities` api supports 1 optional filter parameter for filtering list results: **teachingMode** (`Enum`): Filter by teachingMode - Single: `?teachingMode=` (case-insensitive) - Multiple: `?teachingMode=&teachingMode=` - Null: `?teachingMode=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/listavailabilities/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/listavailabilities/${tutorProfileId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // teachingMode: '' // Filter by teachingMode } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availabilities", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "availabilities": [ { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Lessonslot` API **Rest Route** The `createLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots` **Rest Request Parameters** The `createLessonSlot` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | false | request.body?.["studentId"] | | scheduledDate | Date | true | request.body?.["scheduledDate"] | | scheduledTime | String | true | request.body?.["scheduledTime"] | | status | Enum | true | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | true | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | **coursePackId** : FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. **studentId** : FK to auth:user (student). Set on booking. Nullable when open (free). **scheduledDate** : Date for the lesson slot (yyyy-mm-dd). **scheduledTime** : Start time of lesson (HH:mm 24h). **status** : State of lesson slot (free, booked, completed, canceled). **locationType** : **locationDetails** : Optional: Location address/details; editable after booking by either party. **sessionMode** : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. **meetLink** : Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/lessonslots** ```js axios({ method: 'POST', url: '/v1/lessonslots', data: { coursePackId:"ID", studentId:"ID", scheduledDate:"Date", scheduledTime:"String", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Lessonslot` API **[Default update API]** — This is the designated default `update` API for the `lessonSlot` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update lesson slot status/location. Tutor can edit any of their coursePack's slots; student can update their own booked slot location (if booked). Admin has override right. **Rest Route** The `updateLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `updateLessonSlot` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | | studentId | ID | false | request.body?.["studentId"] | | status | Enum | false | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | false | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | **lessonSlotId** : This id paremeter is used to select the required data object that will be updated **studentId** : FK to auth:user (student). Set on booking. Nullable when open (free). **status** : State of lesson slot (free, booked, completed, canceled). **locationType** : **locationDetails** : Optional: Location address/details; editable after booking by either party. **sessionMode** : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. **meetLink** : Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'PATCH', url: `/v1/lessonslots/${lessonSlotId}`, data: { studentId:"ID", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Lessonslot` API **[Default delete API]** — This is the designated default `delete` API for the `lessonSlot` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor can remove their own slot if free/booked. Admin can remove any. (Student may not delete). **Rest Route** The `deleteLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `deleteLessonSlot` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | **lessonSlotId** : 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/lessonslots/:lessonSlotId** ```js axios({ method: 'DELETE', url: `/v1/lessonslots/${lessonSlotId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Lessonslot` API **Rest Route** The `getLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `getLessonSlot` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | **lessonSlotId** : 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/lessonslots/:lessonSlotId** ```js axios({ method: 'GET', url: `/v1/lessonslots/${lessonSlotId}`, 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": "lessonSlot", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "isActive": true } } ``` ### `List Lessonslots` API **Rest Route** The `listLessonSlots` API REST controller can be triggered via the following route: `/v1/lessonslots` **Rest Request Parameters** The `listLessonSlots` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/lessonslots** ```js axios({ method: 'GET', url: '/v1/lessonslots', 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": "lessonSlots", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "lessonSlots": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Preliminarymeeting` API **[Default create API]** — This is the designated default `create` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student requests a screening meeting; only created if related coursePack requires screening. **Rest Route** The `createPreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings` **Rest Request Parameters** The `createPreliminaryMeeting` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | true | request.body?.["studentId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | true | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | **coursePackId** : FK to tutorCatalog:coursePack (the advanced course) **studentId** : FK to auth:user (student who requested). **scheduledDatetime** : Datetime for screening meeting; may be null until both parties agree. **tutorDecision** : **comments** : Optional field for tutor to provide comments/notes about screening result. **meetingLink** : Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/preliminarymeetings** ```js axios({ method: 'POST', url: '/v1/preliminarymeetings', data: { coursePackId:"ID", studentId:"ID", scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "coursePack": {}, "tutorProfile": {}, "tutorUser": {}, "student": {} } ``` ### `Update Preliminarymeeting` API **[Default update API]** — This is the designated default `update` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates scheduled date/time, decision, or comments for screening meeting. Only tutor of coursePack or admin can approve/reject/set date; student can only propose initial. **Rest Route** The `updatePreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` **Rest Request Parameters** The `updatePreliminaryMeeting` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | false | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | **preliminaryMeetingId** : This id paremeter is used to select the required data object that will be updated **scheduledDatetime** : Datetime for screening meeting; may be null until both parties agree. **tutorDecision** : **comments** : Optional field for tutor to provide comments/notes about screening result. **meetingLink** : Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'PATCH', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "student": {}, "coursePack": {} } ``` ### `Get Preliminarymeeting` API **[Default get API]** — This is the designated default `get` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single meeting by id: only tutor, student, or admin can access. **Rest Route** The `getPreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` **Rest Request Parameters** The `getPreliminaryMeeting` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | **preliminaryMeetingId** : 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/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'GET', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Preliminarymeetings` API **[Default list API]** — This is the designated default `list` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor can list all meetings for their courses; students see their own; admin sees all. **Rest Route** The `listPreliminaryMeetings` API REST controller can be triggered via the following route: `/v1/preliminarymeetings` **Rest Request Parameters** The `listPreliminaryMeetings` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/preliminarymeetings** ```js axios({ method: 'GET', url: '/v1/preliminarymeetings', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeetings", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "preliminaryMeetings": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "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.** --- ## EnrollmentManagement Service # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - EnrollmentManagement Service** This document is a part of a REST API guide for the tutorhub 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 enrollmentManagement ## Service Access EnrollmentManagement service management is handled through service specific base urls. EnrollmentManagement 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 enrollmentManagement service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api` * **Production:** `https://tutorhub.mindbricks.co/enrollmentmanagement-api` ## Scope **EnrollmentManagement Service Description** Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. EnrollmentManagement service provides apis and business logic for following data objects in tutorhub 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. **`enrollment` Data Object**: Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. **`refundRequest` Data Object**: A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. **`sys_enrollmentPayment` Data Object**: A payment storage object to store the payment life cyle of orders based on enrollment 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 ## EnrollmentManagement Service Frontend Description By The Backend Architect Students select a course pack along with desired lesson slots and submit for enrollment. Immediate payment is usually required, except when a preliminary screening meeting is enforced. Enrollment status (pending/active/canceled), payment status, and all associated lesson/slot statuses are visible to the student and tutor. Refund option is ONLY available after the very first lesson has been completed and cannot be requested after subsequent lessons—refunds are auto-processed. Admins view all transactions and refunds, but only students can initiate their own refund request (within policy limits). Tutors and students are both notified of key state changes via frontend mechanisms. No direct deletion of enrollments, only status transition is possible. ## 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" } ``` ## Enrollment Data Object Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. ### Enrollment Data Object Frontend Description By The Backend Architect Students enroll by selecting a course pack and one or more lesson slots; payment is processed online. Enrollment status and payment status are tracked. Refund eligibility only opens after student attends first lesson. All major state changes (enrollment, payment, refund) are exposed to the student, tutor, and admin for transparency. ### Enrollment Data Object Properties Enrollment 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 | |----------|------|---------|----------|--------|-------------| | `coursePackId` | ID | false | Yes | No | FK to purchased course pack. | | `studentId` | ID | false | Yes | No | FK to enrolling student (auth:user). | | `tutorProfileId` | ID | false | Yes | No | FK to the course's tutorProfile for admin/analytics. | | `lessonSlotIds` | ID | true | Yes | No | IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). | | `totalAmount` | Double | false | Yes | No | Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). | | `currency` | String | false | Yes | No | 3-letter ISO currency code (e.g., 'USD', 'EUR'). | | `paymentStatus` | Enum | | Yes | No | Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation). | | `refundStatus` | Enum | false | Yes | No | Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. | | `enrollmentStatus` | Enum | | Yes | No | Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated). | | `enrolledAt` | Date | false | No | No | Datetime of completed enrollment (post-payment). | | `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. ### Array Properties `lessonSlotIds` Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed. ### 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. - **paymentStatus**: [pending, paid, refunded] - **refundStatus**: [notRequested, eligible, processed, ineligible] - **enrollmentStatus**: [pending, active, completed, canceled] - **paymentConfirmation**: [pending, processing, paid, canceled] ### Relation Properties `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` 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. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **lessonSlotIds**: ID Relation to `lessonSlot`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### 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` ## RefundRequest Data Object A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. ### RefundRequest Data Object Frontend Description By The Backend Architect A student may file a refund request ONLY after their first lesson, and only if no later lessons have been completed. The request is automatically approved and processed via Stripe. Only one refund is processed per enrollment. Admins and tutors are notified when refunds occur. Refund status is visible to students and staff for transparency and audit. ### RefundRequest Data Object Properties RefundRequest 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 | |----------|------|---------|----------|--------|-------------| | `enrollmentId` | ID | false | Yes | No | FK to enrollment object for which refund is being requested (unique: one refund per enrollment). | | `requestedBy` | ID | false | Yes | No | User (student) making the refund request (auth:user id). | | `requestedAt` | Date | false | Yes | No | Datetime refund was requested. | | `processedAt` | Date | false | No | No | When refund was processed by system (auto-approval). | | `status` | Enum | false | Yes | No | Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). | | `reason` | String | false | Yes | No | User-supplied reason for requesting refund. | | `firstLessonCompleted` | Boolean | false | Yes | No | True if this refund is after first lesson (enforced by workflow); must be checked before approval. | | `adminNote` | String | false | No | No | Admin note explaining the refund decision (approve/reject reason). | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, 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, autoApproved] ### Relation Properties `enrollmentId` `requestedBy` 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. - **enrollmentId**: ID Relation to `enrollment`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **requestedBy**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ## Sys_enrollmentPayment Data Object A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object's checkout config ### Sys_enrollmentPayment Data Object Properties Sys_enrollmentPayment 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 enrollment 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. ### Enrollment Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createEnrollment` | `/v1/enrollments` | Yes | | Update | `cancelEnrollment` | `/v1/cancelenrollment/:enrollmentId` | Auto | | Delete | _none_ | - | Auto | | Get | `getEnrollment` | `/v1/enrollments/:enrollmentId` | Yes | | List | `listEnrollments` | `/v1/enrollments` | Yes | ### RefundRequest Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createRefundRequest` | `/v1/refundrequests` | Yes | | Update | `updateRefundRequest` | `/v1/refundrequests/:refundRequestId` | Yes | | Delete | _none_ | - | Auto | | Get | `getRefundRequest` | `/v1/refundrequests/:refundRequestId` | Yes | | List | `listRefundRequests` | `/v1/refundrequests` | Yes | ### Sys_enrollmentPayment Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createEnrollmentPayment` | `/v1/enrollmentpayment` | Auto | | Update | `updateEnrollmentPayment` | `/v1/enrollmentpayment/:sys_enrollmentPaymentId` | Auto | | Delete | `deleteEnrollmentPayment` | `/v1/enrollmentpayment/:sys_enrollmentPaymentId` | Auto | | Get | `getEnrollmentPayment` | `/v1/enrollmentpayment/:sys_enrollmentPaymentId` | Auto | | List | `listEnrollmentPayments` | `/v1/enrollmentpayments` | 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 Enrollment` API **[Default create API]** — This is the designated default `create` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Creates a new enrollment for a student in a selected course pack and selected lesson slots. Enforces booking prerequisites (availability, non-duplication, preliminary meeting if flagged in coursePack), and triggers Stripe payment. Updates all associated lesson slot statuses to booked. Enrollment remains pending until payment confirmed by Stripe webhook. **API Frontend Description By The Backend Architect** Student chooses course pack, selects lesson slots, triggers enrollment and Stripe payment. If the course requires preliminary screening, checks that it was passed before proceeding. If payment fails, booking is not confirmed. Successful booking sets lesson slots status to 'booked' and opens enrollment. Student, tutor, and admin can see details. **Rest Route** The `createEnrollment` API REST controller can be triggered via the following route: `/v1/enrollments` **Rest Request Parameters** The `createEnrollment` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | lessonSlotIds | ID | true | request.body?.["lessonSlotIds"] | | totalAmount | Double | true | request.body?.["totalAmount"] | | currency | String | true | request.body?.["currency"] | | refundStatus | Enum | true | request.body?.["refundStatus"] | | enrolledAt | Date | false | request.body?.["enrolledAt"] | **coursePackId** : FK to purchased course pack. **tutorProfileId** : FK to the course's tutorProfile for admin/analytics. **lessonSlotIds** : IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). **totalAmount** : Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). **currency** : 3-letter ISO currency code (e.g., 'USD', 'EUR'). **refundStatus** : Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. **enrolledAt** : Datetime of completed enrollment (post-payment). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/enrollments** ```js axios({ method: 'POST', url: '/v1/enrollments', data: { coursePackId:"ID", tutorProfileId:"ID", lessonSlotIds:"ID", totalAmount:"Double", currency:"String", refundStatus:"Enum", enrolledAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Enrollment` API **[Default get API]** — This is the designated default `get` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single enrollment, including all details and linked objects (student, coursePack, lessonSlots). Only the enrollment's student, tutor, or admin may view. **API Frontend Description By The Backend Architect** Enrollment owners (student), relevant tutor, and admin can see all details of an enrollment via this API. Contains lesson slot list, linked pack, payment/refund status, fulfillment states for transparency. **Rest Route** The `getEnrollment` API REST controller can be triggered via the following route: `/v1/enrollments/:enrollmentId` **Rest Request Parameters** The `getEnrollment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | **enrollmentId** : 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/enrollments/:enrollmentId** ```js axios({ method: 'GET', url: `/v1/enrollments/${enrollmentId}`, 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": "enrollment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "enrollment": { "coursePack": { "tutorProfileId": "ID", "title": "String", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer" }, "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String" }, {}, {} ], "student": { "fullname": "String", "avatar": "String" }, "tutorProfile": { "tutorId": "ID", "certifications": "String", "bio": "Text", "profilePhoto": "String" }, "isActive": true } } ``` ### `List Enrollments` API **[Default list API]** — This is the designated default `list` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all enrollments. Admin sees all; students see their enrollments; tutors see enrollments where their tutorProfileId matches. **API Frontend Description By The Backend Architect** Admins see all enrollments; students see their own; tutors can filter enrollments to their packs by tutorProfileId. Response is enriched with embedded course, lesson, and user details as requested by the frontend. **Rest Route** The `listEnrollments` API REST controller can be triggered via the following route: `/v1/enrollments` **Rest Request Parameters** The `listEnrollments` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | false | request.query?.["tutorProfileId"] | **tutorProfileId** : Optional tutor profile ID filter for tutors to see enrollments in their courses. **Filter Parameters** The `listEnrollments` api supports 1 optional filter parameter for filtering list results: **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/enrollments** ```js axios({ method: 'GET', url: '/v1/enrollments', data: { }, params: { tutorProfileId:'"ID"', // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "coursePack": [ { "title": "String", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "isActive": true }, {}, {} ], "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer" }, {}, {} ], "student": [ { "email": "String", "fullname": "String", "avatar": "String" }, {}, {} ], "tutorProfile": [ { "tutorId": "ID", "bio": "Text" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Refundrequest` API **[Default create API]** — This is the designated default `create` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student files refund request for a completed enrollment only after first lesson and only if no additional lessons are complete. Auto-approves, updates enrollment statuses, and triggers Stripe refund if eligible. **API Frontend Description By The Backend Architect** Students can trigger a refund for their enrollment only after first lesson, provided no additional lessons have been completed. The refund is auto-approved and reflected in both user's and admin's views; tutor and admin are notified. No manual approval or asynchronous queue, strictly within narrow business criteria. **Rest Route** The `createRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests` **Rest Request Parameters** The `createRefundRequest` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.body?.["enrollmentId"] | | requestedAt | Date | true | request.body?.["requestedAt"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | true | request.body?.["status"] | | reason | String | true | request.body?.["reason"] | | firstLessonCompleted | Boolean | true | request.body?.["firstLessonCompleted"] | | adminNote | String | false | request.body?.["adminNote"] | **enrollmentId** : FK to enrollment object for which refund is being requested (unique: one refund per enrollment). **requestedAt** : Datetime refund was requested. **processedAt** : When refund was processed by system (auto-approval). **status** : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). **reason** : User-supplied reason for requesting refund. **firstLessonCompleted** : True if this refund is after first lesson (enforced by workflow); must be checked before approval. **adminNote** : Admin note explaining the refund decision (approve/reject reason). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/refundrequests** ```js axios({ method: 'POST', url: '/v1/refundrequests', data: { enrollmentId:"ID", requestedAt:"Date", processedAt:"Date", status:"Enum", reason:"String", firstLessonCompleted:"Boolean", adminNote:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Refundrequest` API **[Default get API]** — This is the designated default `get` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get refund request record for audit—visible to student (their own), tutor (if their course), or admin. Linked enrollment, user, and status are included. **API Frontend Description By The Backend Architect** Students check status of their refund request; tutors may audit if linked to their courses; admins can view all. Details include enrollment and state for auditing. **Rest Route** The `getRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests/:refundRequestId` **Rest Request Parameters** The `getRefundRequest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | **refundRequestId** : 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/refundrequests/:refundRequestId** ```js axios({ method: 'GET', url: `/v1/refundrequests/${refundRequestId}`, 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": "refundRequest", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "refundRequest": { "enrollment": { "coursePackId": "ID", "studentId": "ID" }, "isActive": true } } ``` ### `List Refundrequests` API **[Default list API]** — This is the designated default `list` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all refund requests (students see their own, admins see all, tutors see linked to their courses via coursePack). **API Frontend Description By The Backend Architect** Admins list all refund requests; students see their submitted refunds; tutors see those linked to their courses for reporting and audit. Each item shows enrollment link and high-level audit fields. **Rest Route** The `listRefundRequests` API REST controller can be triggered via the following route: `/v1/refundrequests` **Rest Request Parameters** The `listRefundRequests` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/refundrequests** ```js axios({ method: 'GET', url: '/v1/refundrequests', 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": "refundRequests", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "refundRequests": [ { "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "totalAmount": "Double", "currency": "String" }, {}, {} ], "coursePack": { "title": "String" }, "requester": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Refundrequest` API **[Default update API]** — This is the designated default `update` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin updates a refund request: approve or reject with an admin note. Only admins can update refund requests. **API Frontend Description By The Backend Architect** Admin-only endpoint for processing pending refund requests. Admin sets status to approved or rejected and optionally provides an adminNote explaining the decision. processedAt is set automatically on approval/rejection. **Rest Route** The `updateRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests/:refundRequestId` **Rest Request Parameters** The `updateRefundRequest` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | **refundRequestId** : This id paremeter is used to select the required data object that will be updated **processedAt** : When refund was processed by system (auto-approval). **status** : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). **adminNote** : Admin note explaining the refund decision (approve/reject reason). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refundrequests/:refundRequestId** ```js axios({ method: 'PATCH', url: `/v1/refundrequests/${refundRequestId}`, data: { processedAt:"Date", status:"Enum", adminNote:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Cancel Enrollment` API Admin force-cancels an enrollment. Sets enrollmentStatus to canceled, paymentStatus to refunded, refundStatus to processed. Used when a tutor is banned/suspended or a course is removed. **API Frontend Description By The Backend Architect** Admin-only action to force-cancel an enrollment. Used when tutor is banned, suspended, or course is removed. **Rest Route** The `cancelEnrollment` API REST controller can be triggered via the following route: `/v1/cancelenrollment/:enrollmentId` **Rest Request Parameters** The `cancelEnrollment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | cancelReason | String | | request.body?.["cancelReason"] | **enrollmentId** : This id paremeter is used to select the required data object that will be updated **cancelReason** : Admin reason for canceling the enrollment **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/cancelenrollment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/cancelenrollment/${enrollmentId}`, data: { cancelReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Admin Refundenrollment` API Admin-initiated refund for an enrollment. Creates a refundRequest with autoApproved status, cancels the enrollment, and triggers Stripe refund. No student eligibility checks — admin override. **API Frontend Description By The Backend Architect** Admin-only action to refund an enrollment on behalf of a student. Used when tutor is banned/suspended, course removed, or admin decides a refund is warranted. The enrollment is immediately canceled and a refund request record is created for audit. **Rest Route** The `adminRefundEnrollment` API REST controller can be triggered via the following route: `/v1/adminrefundenrollment` **Rest Request Parameters** The `adminRefundEnrollment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | | reason | String | | request.body?.["reason"] | **enrollmentId** : The enrollment to refund **reason** : Admin reason for issuing the refund **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminrefundenrollment** ```js axios({ method: 'POST', url: '/v1/adminrefundenrollment', data: { enrollmentId:"ID", reason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Cascade Tutorban` API Admin cascade: cancel all active enrollments for a banned/suspended tutor. **API Frontend Description By The Backend Architect** Called after admin bans or suspends a tutor. Cancels all active enrollments and frees slots. **Rest Route** The `cascadeTutorBan` API REST controller can be triggered via the following route: `/v1/cascadetutorban` **Rest Request Parameters** The `cascadeTutorBan` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | reason | String | | request.body?.["reason"] | **tutorProfileId** : The tutor profile whose enrollments should be canceled **reason** : Reason for cascade cancellation **Filter Parameters** The `cascadeTutorBan` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/cascadetutorban** ```js axios({ method: 'POST', url: '/v1/cascadetutorban', data: { tutorProfileId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Cascade Courseremoval` API Admin cascade: cancel all active enrollments for a removed course pack. **API Frontend Description By The Backend Architect** Called after admin removes a course. Cancels all active enrollments and frees slots. **Rest Route** The `cascadeCourseRemoval` API REST controller can be triggered via the following route: `/v1/cascadecourseremoval` **Rest Request Parameters** The `cascadeCourseRemoval` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | | request.body?.["coursePackId"] | | reason | String | | request.body?.["reason"] | **coursePackId** : The course pack whose enrollments should be canceled **reason** : Reason for cascade cancellation **Filter Parameters** The `cascadeCourseRemoval` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/cascadecourseremoval** ```js axios({ method: 'POST', url: '/v1/cascadecourseremoval', data: { coursePackId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Cleanup Pendingenrollments` API Cleanup stale pending enrollments that were never paid. Cancels them and frees lesson slots. Default timeout: 60 minutes. **API Frontend Description By The Backend Architect** Admin or system cron calls this to clean up abandoned enrollments. Can also be triggered from frontend as a housekeeping action. **Rest Route** The `cleanupPendingEnrollments` API REST controller can be triggered via the following route: `/v1/cleanuppendingenrollments` **Rest Request Parameters** The `cleanupPendingEnrollments` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | maxAgeMinutes | Integer | | request.body?.["maxAgeMinutes"] | **maxAgeMinutes** : How old (in minutes) a pending enrollment must be to get cleaned up. Default: 60 **Filter Parameters** The `cleanupPendingEnrollments` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/cleanuppendingenrollments** ```js axios({ method: 'POST', url: '/v1/cleanuppendingenrollments', data: { maxAgeMinutes:"Integer", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Check Enrollmentcompletion` API Check if all lesson slots in an enrollment are completed and mark enrollment as completed if so. **API Frontend Description By The Backend Architect** Called after a lesson is marked completed. Checks if all lessons are done and auto-completes the enrollment. **Rest Route** The `checkEnrollmentCompletion` API REST controller can be triggered via the following route: `/v1/checkenrollmentcompletion` **Rest Request Parameters** The `checkEnrollmentCompletion` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | **enrollmentId** : The enrollment to check for completion **Filter Parameters** The `checkEnrollmentCompletion` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/checkenrollmentcompletion** ```js axios({ method: 'POST', url: '/v1/checkenrollmentcompletion', data: { enrollmentId:"ID", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Get Enrollmentpayment` API This route is used to get the payment information by ID. **Rest Route** The `getEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `getEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | **sys_enrollmentPaymentId** : 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayments` API This route is used to list all payments. **Rest Route** The `listEnrollmentPayments` API REST controller can be triggered via the following route: `/v1/enrollmentpayments` **Rest Request Parameters** **Filter Parameters** The `listEnrollmentPayments` 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 enrollment 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/enrollmentpayments** ```js axios({ method: 'GET', url: '/v1/enrollmentpayments', 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_enrollmentPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_enrollmentPayments": [ { "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 Enrollmentpayment` API This route is used to create a new payment. **Rest Route** The `createEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment` **Rest Request Parameters** The `createEnrollmentPayment` 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 enrollment 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/enrollmentpayment** ```js axios({ method: 'POST', url: '/v1/enrollmentpayment', 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_enrollmentPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` API This route is used to update an existing payment. **Rest Route** The `updateEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `updateEnrollmentPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | | 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_enrollmentPaymentId** : 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'PATCH', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` API This route is used to delete a payment. **Rest Route** The `deleteEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `deleteEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | **sys_enrollmentPaymentId** : 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'DELETE', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getEnrollmentPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/enrollmentpaymentbyorderid/:orderId` **Rest Request Parameters** The `getEnrollmentPaymentByOrderId` 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 enrollment 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/enrollmentpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbyorderid/${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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getEnrollmentPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/enrollmentpaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getEnrollmentPaymentByPaymentId` 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/enrollmentpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbypaymentid/${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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` API Start payment for enrollment **Rest Route** The `startEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/startenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `startEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **enrollmentId** : 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/startenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/startenrollmentpayment/${enrollmentId}`, 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 Enrollmentpayment` API Refresh payment info for enrollment from Stripe **Rest Route** The `refreshEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/refreshenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `refreshEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **enrollmentId** : 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/refreshenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/refreshenrollmentpayment/${enrollmentId}`, 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 Enrollmentpayment` API Refresh payment values by gateway webhook call for enrollment **Rest Route** The `callbackEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/callbackenrollmentpayment` **Rest Request Parameters** The `callbackEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | false | request.body?.["enrollmentId"] | **enrollmentId** : 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/callbackenrollmentpayment** ```js axios({ method: 'POST', url: '/v1/callbackenrollmentpayment', data: { enrollmentId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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.** --- ## EnrollmentManagement Service Enrollment Payment Flow # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - EnrollmentManagement Service Enrollment Payment Flow** This document is a part of a REST API guide for the tutorhub project. It is designed for AI agents that will generate frontend code to consume the project’s backend. ## Stripe Payment Flow For Enrollment `Enrollment` 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 `enrollmentId` 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 Tutorhub 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 `enrollmentManagement` 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 `enrollmentManagement` service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api` * **Production:** `https://tutorhub.mindbricks.co/enrollmentmanagement-api` ## Creating the Enrollment While creating the `enrollment` 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 `enrollment`). 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 `totalAmount` 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(() => (`Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}`), {"path":"services[3].dataObjects[0].objectSettings.stripeOrder.configuration.description"})`. - `orderStatusProperty`: `paymentStatus` is updated automatically by the payment flow using a mapped status value. - `orderStatusUpdateDateProperty`: `updatedAt` stores the timestamp of the latest payment status update. - `orderOwnerIdProperty`: `studentId` 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[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted"})` **paymentResultCanceled**: `runMScript(() => ("pending"), {"path":"services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled"})` **paymentResultFailed**: `runMScript(() => ("pending"), {"path":"services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed"})` **paymentResultSuccess**: `runMScript(() => ("paid"), {"path":"services[3].dataObjects[0].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 `enrollment` 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 Tutorhub 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 `startEnrollmentPayment` 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 `startEnrollmentPayment` API is a versioned **Business Logic API** and follows the same structure as other business APIs. In the Tutorhub 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 `startEnrollmentPayment` API is called, the response will include a successful or failed PaymentIntent result inside the `paymentResult` object, along with the `enrollment` 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 `startEnrollmentPayment` API contains the data necessary to create the Stripe PaymentIntent. Call the API as follows: ```js const response = await fetch( `$serviceUrl/v1/startenrollmentpayment/${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 Enrollmentpayment` API Start payment for enrollment **Rest Route** The `startEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/startenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `startEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **enrollmentId** : 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/startenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/startenrollmentpayment/${enrollmentId}`, 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 `startEnrollmentPayment` 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", "enrollment": { "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 `enrollment` 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 `enrollmentId` 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 `startEnrollmentPayment` 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 `enrollment` instance from the backend to display any additional order or fulfillment details. Note that paymentIntent status only gives information about the Stripe side. The `enrollment` instance in the service should also ve updated to start the fulfillment. In most cases, the `startenrollmentPayment` 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 `enrollment. To ensure that service i To fetch the `enrollment` 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 `enrollment` instance. ```js if (enrollment.paymentConfirmation == "canceled") { // the payment is canceled, user can be informed that they should try again } if (enrollment.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 `enrollmentManagement` 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": "enrollment", "serviceName": "enrollmentManagement", "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. --- ## PlatformAdmin Service # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - PlatformAdmin Service** This document is a part of a REST API guide for the tutorhub 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 platformAdmin ## Service Access PlatformAdmin service management is handled through service specific base urls. PlatformAdmin 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 platformAdmin service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/platformadmin-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/platformadmin-api` * **Production:** `https://tutorhub.mindbricks.co/platformadmin-api` ## Scope **PlatformAdmin Service Description** PlatformAdmin service provides apis and business logic for following data objects in tutorhub 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. **`adminIssue` Data Object**: **`adminModerationAction` Data Object**: Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. **`adminAnalyticsReport` Data Object**: Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. ## 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" } ``` ## AdminIssue Data Object ### AdminIssue Data Object Properties AdminIssue 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 | |----------|------|---------|----------|--------|-------------| | `reportedBy` | ID | false | Yes | No | User who filed the issue (student or tutor). | | `reportedUserId` | ID | false | No | No | (Optional) User being complained about | | `coursePackId` | ID | false | No | No | (Optional) ID of the related coursePack, if content/pack is complained about | | `description` | Text | false | Yes | No | Long text/body of the complaint/issue. | | `issueType` | Enum | false | Yes | No | Type of complaint (user, content, or other). | | `status` | Enum | false | Yes | No | Issue investigation status (open/investigating/resolved/dismissed). | | `adminNote` | String | false | No | No | Internal/admin note for progress or findings (not visible to original user). | | `resolution` | Enum | false | No | No | Resolution outcome chosen by admin when closing the issue. | * 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. - **issueType**: [user, content, other] - **status**: [open, investigating, resolved, dismissed] - **resolution**: [dismissed, warned, courseEditRequired, courseRemoved, userSuspended, userBanned, acknowledged] ### Relation Properties `reportedBy` `reportedUserId` `coursePackId` 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. - **reportedBy**: 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 - **reportedUserId**: 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: No - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ## AdminModerationAction Data Object Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. ### AdminModerationAction Data Object Frontend Description By The Backend Architect Displays admin content/user moderation events in the admin dashboard. Lists should show each action (targetType, admin, reason, date), target details, and allow filtering by actionType/status/date. ### AdminModerationAction Data Object Properties AdminModerationAction 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 | |----------|------|---------|----------|--------|-------------| | `adminId` | ID | false | Yes | No | Admin performing moderation action. | | `targetType` | Enum | false | Yes | No | Moderation target type (user/coursePack/profile/material). | | `targetId` | ID | false | Yes | No | ID of moderation target object (userId, coursePackId, etc). | | `actionType` | Enum | false | Yes | No | Type of moderation action (suspend, ban, edit, remove, approve, warn). | | `actionReason` | String | false | Yes | No | Reason for moderation action, as recorded by the admin. | | `actionDate` | Date | false | Yes | No | Datetime when the action took place. | | `targetUserId` | ID | false | Yes | No | UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content. | * 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. - **targetType**: [user, coursePack, profile, material] - **actionType**: [suspend, ban, edit, remove, approve, warn] ### Relation Properties `adminId` `targetUserId` 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. - **adminId**: 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 - **targetUserId**: 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 ## AdminAnalyticsReport Data Object Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. ### AdminAnalyticsReport Data Object Frontend Description By The Backend Architect Internal; used as a registry/audit of analytics report generations. List in admin dashboard with download access by reportType/date. Future versions may trigger report generation via edge controllers. ### AdminAnalyticsReport Data Object Properties AdminAnalyticsReport 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 | |----------|------|---------|----------|--------|-------------| | `reportType` | String | false | Yes | No | Type of the analytics report (enrollments, revenue, complaints, etc). | | `filterParams` | String | false | No | No | Filter params as stringified JSON for reporting input. | | `generatedAt` | Date | false | Yes | No | Date/time report was generated. | | `reportUrl` | String | false | Yes | No | Accessible URL where generated report is stored (PDF, CSV, etc). | * 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. ## 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. ### AdminIssue Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAdminIssue` | `/v1/adminissues` | Yes | | Update | `updateAdminIssue` | `/v1/adminissues/:adminIssueId` | Yes | | Delete | _none_ | - | Auto | | Get | `getAdminIssue` | `/v1/adminissues/:adminIssueId` | Yes | | List | `listAdminIssues` | `/v1/adminissues` | Yes | ### AdminModerationAction Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAdminModerationAction` | `/v1/adminmoderationactions` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getAdminModerationAction` | `/v1/adminmoderationactions/:adminModerationActionId` | Yes | | List | `listAdminModerationActions` | `/v1/adminmoderationactions` | Yes | ### AdminAnalyticsReport Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAdminAnalyticsReport` | `/v1/adminanalyticsreports` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getAdminAnalyticsReport` | `/v1/adminanalyticsreports/:adminAnalyticsReportId` | Yes | | List | `listAdminAnalyticsReports` | `/v1/adminanalyticsreports` | 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 ### `Create Adminissue` API **[Default create API]** — This is the designated default `create` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student or tutor files a new complaint/issue. Admin receives for review/investigation. Only admins can update or alter status; creator can get their own. **Rest Route** The `createAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues` **Rest Request Parameters** The `createAdminIssue` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportedBy | ID | true | request.body?.["reportedBy"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | true | request.body?.["description"] | | issueType | Enum | true | request.body?.["issueType"] | | status | Enum | true | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | **reportedBy** : User who filed the issue (student or tutor). **reportedUserId** : (Optional) User being complained about **coursePackId** : (Optional) ID of the related coursePack, if content/pack is complained about **description** : Long text/body of the complaint/issue. **issueType** : Type of complaint (user, content, or other). **status** : Issue investigation status (open/investigating/resolved/dismissed). **adminNote** : Internal/admin note for progress or findings (not visible to original user). **resolution** : Resolution outcome chosen by admin when closing the issue. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminissues** ```js axios({ method: 'POST', url: '/v1/adminissues', data: { reportedBy:"ID", reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Adminissue` API **[Default update API]** — This is the designated default `update` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin investigates/updates an issue: change status, add internal note, resolve/dismiss. Strictly admin-only. **Rest Route** The `updateAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues/:adminIssueId` **Rest Request Parameters** The `updateAdminIssue` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | false | request.body?.["description"] | | issueType | Enum | false | request.body?.["issueType"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | **adminIssueId** : This id paremeter is used to select the required data object that will be updated **reportedUserId** : (Optional) User being complained about **coursePackId** : (Optional) ID of the related coursePack, if content/pack is complained about **description** : Long text/body of the complaint/issue. **issueType** : Type of complaint (user, content, or other). **status** : Issue investigation status (open/investigating/resolved/dismissed). **adminNote** : Internal/admin note for progress or findings (not visible to original user). **resolution** : Resolution outcome chosen by admin when closing the issue. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/adminissues/:adminIssueId** ```js axios({ method: 'PATCH', url: `/v1/adminissues/${adminIssueId}`, data: { reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "reporterUser": {} } ``` ### `Get Adminissue` API **[Default get API]** — This is the designated default `get` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetches a single issue by ID. Admins may get any; creator may get/view their own for status updates. **Rest Route** The `getAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues/:adminIssueId` **Rest Request Parameters** The `getAdminIssue` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | **adminIssueId** : 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/adminissues/:adminIssueId** ```js axios({ method: 'GET', url: `/v1/adminissues/${adminIssueId}`, 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": "adminIssue", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminIssue": { "reporter": { "email": "String", "fullname": "String" }, "reportedUser": { "email": "String", "fullname": "String" }, "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` ### `List Adminissues` API **[Default list API]** — This is the designated default `list` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List issues with filters for admin dashboard: by status/type/target. Admin only. **Rest Route** The `listAdminIssues` API REST controller can be triggered via the following route: `/v1/adminissues` **Rest Request Parameters** The `listAdminIssues` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminissues** ```js axios({ method: 'GET', url: '/v1/adminissues', 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": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reporter": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "reportedUser": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Adminmoderationaction` API **[Default create API]** — This is the designated default `create` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin records a moderation action against a user/object. Admin only. Write-side audit log for all moderator events. **Rest Route** The `createAdminModerationAction` API REST controller can be triggered via the following route: `/v1/adminmoderationactions` **Rest Request Parameters** The `createAdminModerationAction` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminId | ID | true | request.body?.["adminId"] | | targetType | Enum | true | request.body?.["targetType"] | | targetId | ID | true | request.body?.["targetId"] | | actionType | Enum | true | request.body?.["actionType"] | | actionReason | String | true | request.body?.["actionReason"] | | actionDate | Date | true | request.body?.["actionDate"] | | targetUserId | ID | true | request.body?.["targetUserId"] | **adminId** : Admin performing moderation action. **targetType** : Moderation target type (user/coursePack/profile/material). **targetId** : ID of moderation target object (userId, coursePackId, etc). **actionType** : Type of moderation action (suspend, ban, edit, remove, approve, warn). **actionReason** : Reason for moderation action, as recorded by the admin. **actionDate** : Datetime when the action took place. **targetUserId** : UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminmoderationactions** ```js axios({ method: 'POST', url: '/v1/adminmoderationactions', data: { adminId:"ID", targetType:"Enum", targetId:"ID", actionType:"Enum", actionReason:"String", actionDate:"Date", targetUserId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminModerationAction", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "id": "ID", "adminId": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "actionType": "Enum", "actionType_idx": "Integer", "actionReason": "String", "actionDate": "Date", "targetUserId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "targetUser": {} } ``` ### `Get Adminmoderationaction` API **[Default get API]** — This is the designated default `get` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one moderation action. Admin only. **Rest Route** The `getAdminModerationAction` API REST controller can be triggered via the following route: `/v1/adminmoderationactions/:adminModerationActionId` **Rest Request Parameters** The `getAdminModerationAction` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminModerationActionId | ID | true | request.params?.["adminModerationActionId"] | **adminModerationActionId** : 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/adminmoderationactions/:adminModerationActionId** ```js axios({ method: 'GET', url: `/v1/adminmoderationactions/${adminModerationActionId}`, 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": "adminModerationAction", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "admin": { "email": "String", "fullname": "String" }, "isActive": true } } ``` ### `List Adminmoderationactions` API **[Default list API]** — This is the designated default `list` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all admin moderation actions, filterable by actionType/targetType/date. For admin dashboard audit log. **Rest Route** The `listAdminModerationActions` API REST controller can be triggered via the following route: `/v1/adminmoderationactions` **Rest Request Parameters** The `listAdminModerationActions` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminmoderationactions** ```js axios({ method: 'GET', url: '/v1/adminmoderationactions', 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": "adminModerationActions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminModerationActions": [ { "admin": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Adminanalyticsreport` API **[Default create API]** — This is the designated default `create` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create record for a new analytics report (usually admin-triggered on dashboard, actual report process may be async via edge controller in future). Admin-only; records metadata and download URL of available report. **Rest Route** The `createAdminAnalyticsReport` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports` **Rest Request Parameters** The `createAdminAnalyticsReport` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportType | String | true | request.body?.["reportType"] | | filterParams | String | false | request.body?.["filterParams"] | | generatedAt | Date | true | request.body?.["generatedAt"] | | reportUrl | String | true | request.body?.["reportUrl"] | **reportType** : Type of the analytics report (enrollments, revenue, complaints, etc). **filterParams** : Filter params as stringified JSON for reporting input. **generatedAt** : Date/time report was generated. **reportUrl** : Accessible URL where generated report is stored (PDF, CSV, etc). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminanalyticsreports** ```js axios({ method: 'POST', url: '/v1/adminanalyticsreports', data: { reportType:"String", filterParams:"String", generatedAt:"Date", reportUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminAnalyticsReport", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "id": "ID", "reportType": "String", "filterParams": "String", "generatedAt": "Date", "reportUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Adminanalyticsreport` API **[Default get API]** — This is the designated default `get` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one analytics report record for download from admin dashboard. Admin only. **Rest Route** The `getAdminAnalyticsReport` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports/:adminAnalyticsReportId` **Rest Request Parameters** The `getAdminAnalyticsReport` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminAnalyticsReportId | ID | true | request.params?.["adminAnalyticsReportId"] | **adminAnalyticsReportId** : 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/adminanalyticsreports/:adminAnalyticsReportId** ```js axios({ method: 'GET', url: `/v1/adminanalyticsreports/${adminAnalyticsReportId}`, 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": "adminAnalyticsReport", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "isActive": true } } ``` ### `List Adminanalyticsreports` API **[Default list API]** — This is the designated default `list` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all analytics reports for admin dashboard access (download/view). Admin only. **Rest Route** The `listAdminAnalyticsReports` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports` **Rest Request Parameters** The `listAdminAnalyticsReports` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminanalyticsreports** ```js axios({ method: 'GET', url: '/v1/adminanalyticsreports', 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": "adminAnalyticsReports", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminAnalyticsReports": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Myissues` API Students and tutors list their own reported issues. Ownership check ensures users only see their own reports. **Rest Route** The `listMyIssues` API REST controller can be triggered via the following route: `/v1/myissues` **Rest Request Parameters** The `listMyIssues` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myissues** ```js axios({ method: 'GET', url: '/v1/myissues', 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": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reportedUser": [ { "email": "String", "fullname": "String" }, {}, {} ], "coursePack": [ { "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "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.** --- ## Messaging Service # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 12 - Messaging Service** This document is a part of a REST API guide for the tutorhub 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 messaging ## Service Access Messaging service management is handled through service specific base urls. Messaging 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 messaging service, the base URLs are: * **Preview:** `https://tutorhub.prw.mindbricks.com/messaging-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/messaging-api` * **Production:** `https://tutorhub.mindbricks.co/messaging-api` ## Scope **Messaging Service Description** Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. Messaging service provides apis and business logic for following data objects in tutorhub 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. **`conversation` Data Object**: Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). **`chatMessage` Data Object**: Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. **`chatModeration` Data Object**: Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. ## Messaging Service Frontend Description By The Backend Architect ## Messaging Service UX Guide ### Three Channel Types: 1. **Student ↔ Tutor** (studentTutor): Bidirectional chat between enrolled student and their tutor. Created when enrollment becomes active. 2. **Admin → Student** (adminStudent): One-way channel. Admin sends warnings/notices. Student can only read, not reply. 3. **Admin ↔ Tutor** (adminTutor): Bidirectional. Admin sends warnings, tutor can reply/discuss. ### UX Behavior: - Inbox shows all conversations sorted by lastMessageAt descending - Unread badge count per conversation - For adminStudent conversations, hide the message input for students — show a notice: 'This is a notification channel. You cannot reply.' - Warning messages (messageType=warning) should render with a yellow/amber alert style, distinct from regular text messages - System messages render centered, gray, smaller font - Show participant name + avatar in conversation header - Real-time: typing indicators, read receipts, online presence ## 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" } ``` ## Conversation Data Object Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). ### Conversation Data Object Frontend Description By The Backend Architect ## Conversation UX - Each conversation is a private channel between exactly 2 participants - For `studentTutor` type: both parties can send messages. Only exists between enrolled student-tutor pairs. - For `adminStudent` type: admin sends warnings/notices, student can only READ. Hide message input for student, show 'Admin notification channel' banner. - For `adminTutor` type: both admin and tutor can send and read. Tutor can reply to warnings. - Conversation list sorted by `lastMessageAt` descending. - Show unread count badge. - Warning messages (type=warning) render with amber alert styling. ### Conversation Data Object Properties Conversation 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 | |----------|------|---------|----------|--------|-------------| | `conversationType` | String | false | Yes | No | Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. | | `participantA` | ID | false | Yes | No | First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. | | `participantB` | ID | false | Yes | No | Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. | | `enrollmentId` | ID | false | No | No | FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. | | `lastMessageAt` | Date | false | No | No | Timestamp of the most recent message. Used for sorting conversations in inbox. | | `lastMessagePreview` | String | false | No | No | Truncated preview of last message content. Shown in conversation list. | | `status` | String | false | Yes | No | Conversation status: active or closed. | | `participantAName` | String | false | No | No | Cached display name of participant A for quick rendering in conversation list. | | `participantBName` | String | false | No | No | Cached display name of participant B for quick rendering in conversation list. | | `courseTitle` | String | false | No | No | Cached course pack title for display. Set on conversation creation for studentTutor type. | * 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. - **conversationType**: [studentTutor, adminStudent, adminTutor] - **status**: [active, closed] ### Relation Properties `participantA` `participantB` `enrollmentId` 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. - **participantA**: 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 - **participantB**: 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 - **enrollmentId**: ID Relation to `enrollment`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ## ChatMessage Data Object Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. ### 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 | |----------|------|---------|----------|--------|-------------| | `roomId` | ID | false | Yes | No | Reference to the room this message belongs to | | `senderId` | ID | false | No | No | Reference to the user who sent this message | | `senderName` | String | false | No | No | Display name of the sender (denormalized from user profile at send time) | | `senderAvatar` | String | false | No | No | Avatar URL of the sender (denormalized from user profile at send time) | | `messageType` | Enum | false | Yes | No | Content type discriminator for this message | | `content` | Object | false | Yes | No | Type-specific content payload (structure depends on messageType) | | `timestamp` | | false | No | No | Message creation time | | `status` | Enum | false | No | No | Message moderation status | | `replyTo` | Object | false | No | No | Reply thread reference { id, preview } | * 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. - **messageType**: [text, image, document, system, warning] - **status**: [pending, approved, rejected] ### Filter Properties `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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. - **roomId**: ID has a filter named `roomId` - **senderId**: ID has a filter named `senderId` - **senderName**: String has a filter named `senderName` - **senderAvatar**: String has a filter named `senderAvatar` - **messageType**: Enum has a filter named `messageType` - **content**: Object has a filter named `content` - **timestamp**: has a filter named `timestamp` - **status**: Enum has a filter named `status` - **replyTo**: Object has a filter named `replyTo` ## ChatModeration Data Object Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. ### ChatModeration Data Object Properties ChatModeration 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 | |----------|------|---------|----------|--------|-------------| | `roomId` | ID | false | Yes | No | Reference to the room where the moderation action applies | | `userId` | ID | false | Yes | No | The user who is blocked or silenced | | `action` | Enum | false | Yes | No | Moderation action type | | `reason` | Text | false | No | No | Optional reason for the moderation action | | `duration` | Integer | false | No | No | Duration in seconds. 0 means permanent | | `expiresAt` | | false | No | No | Expiry timestamp. Null means permanent | | `issuedBy` | ID | false | No | No | The moderator who issued the action | * 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**: [blocked, silenced] ### Relation Properties `roomId` 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. - **roomId**: ID Relation to `conversation`.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 `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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. - **roomId**: ID has a filter named `roomId` - **userId**: ID has a filter named `userId` - **action**: Enum has a filter named `action` - **reason**: Text has a filter named `reason` - **duration**: Integer has a filter named `duration` - **expiresAt**: has a filter named `expiresAt` - **issuedBy**: ID has a filter named `issuedBy` ## 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. ### Conversation Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createConversation` | `/v1/conversations` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getConversation` | `/v1/conversations/:conversationId` | Yes | | List | `listMyConversations` | `/v1/myconversations` | Yes | ### ChatMessage Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | `updateChatMessage` | `/v1/v1/chat-messages/:id` | Yes | | Delete | `deleteChatMessage` | `/v1/v1/chat-messages/:id` | Yes | | Get | `getChatMessage` | `/v1/v1/chat-messages/:id` | Yes | | List | `listChatMessages` | `/v1/v1/chat-messages` | Yes | ### ChatModeration Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | _none_ | - | Auto | | List | _none_ | - | 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 Conversation` API **[Default create API]** — This is the designated default `create` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Creates a new conversation between two participants. For studentTutor type, requires valid enrollment. For adminStudent/adminTutor, only admin can create. **API Frontend Description By The Backend Architect** ## Create Conversation - Tutors/students can create studentTutor conversations. - Only admin can create adminStudent or adminTutor conversations. - Before creating, check if conversation already exists between the two participants of same type. **Rest Route** The `createConversation` API REST controller can be triggered via the following route: `/v1/conversations` **Rest Request Parameters** The `createConversation` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationType | String | true | request.body?.["conversationType"] | | participantA | ID | true | request.body?.["participantA"] | | participantB | ID | true | request.body?.["participantB"] | | enrollmentId | ID | false | request.body?.["enrollmentId"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | | lastMessagePreview | String | false | request.body?.["lastMessagePreview"] | | participantAName | String | false | request.body?.["participantAName"] | | participantBName | String | false | request.body?.["participantBName"] | | courseTitle | String | false | request.body?.["courseTitle"] | **conversationType** : Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. **participantA** : First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. **participantB** : Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. **enrollmentId** : FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. **lastMessageAt** : Timestamp of the most recent message. Used for sorting conversations in inbox. **lastMessagePreview** : Truncated preview of last message content. Shown in conversation list. **participantAName** : Cached display name of participant A for quick rendering in conversation list. **participantBName** : Cached display name of participant B for quick rendering in conversation list. **courseTitle** : Cached course pack title for display. Set on conversation creation for studentTutor type. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/conversations** ```js axios({ method: 'POST', url: '/v1/conversations', data: { conversationType:"String", participantA:"ID", participantB:"ID", enrollmentId:"ID", lastMessageAt:"Date", lastMessagePreview:"String", participantAName:"String", participantBName:"String", courseTitle:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Conversation` API **[Default get API]** — This is the designated default `get` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single conversation by ID. Only participants or admin can view. **Rest Route** The `getConversation` API REST controller can be triggered via the following route: `/v1/conversations/:conversationId` **Rest Request Parameters** The `getConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | **conversationId** : 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/conversations/:conversationId** ```js axios({ method: 'GET', url: `/v1/conversations/${conversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" } } } ``` ### `List Myconversations` API **[Default list API]** — This is the designated default `list` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Lists all conversations where the current user is a participant. Sorted by lastMessageAt descending. **API Frontend Description By The Backend Architect** ## Inbox / Conversation List - Shows all conversations for the logged-in user sorted by most recent. - Show: other participant name, last message preview, timestamp, unread badge. - For adminStudent type show 'Admin Notice' label. For adminTutor show 'Admin' label. - Clicking opens the chat view. **Rest Route** The `listMyConversations` API REST controller can be triggered via the following route: `/v1/myconversations` **Rest Request Parameters** The `listMyConversations` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myconversations** ```js axios({ method: 'GET', url: '/v1/myconversations', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "conversations": [ { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Send Systemmessage` API Interservice API called by adminPanel for moderation warnings. Creates/finds admin conversation with target user and sends a warning message. M2M only. **API Frontend Description By The Backend Architect** This API is not called from frontend. It is an interservice endpoint for adminPanel to deliver moderation warnings as chat messages. **Rest Route** The `sendSystemMessage` API REST controller can be triggered via the following route: `/v1/sendsystemmessage` **Rest Request Parameters** The `sendSystemMessage` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | targetUserId | ID | true | request.body?.["targetUserId"] | | targetUserRole | String | true | request.body?.["targetUserRole"] | | messageContent | Text | true | request.body?.["messageContent"] | | resolutionType | String | false | request.body?.["resolutionType"] | | complaintId | ID | false | request.body?.["complaintId"] | | severity | String | false | request.body?.["severity"] | **targetUserId** : The userId of the user to send the warning to **targetUserRole** : Role of target: student or tutor. Determines conversation type **messageContent** : The warning message content **resolutionType** : Moderation resolution type: warn, requireEdit, removeCourse, suspend, ban **complaintId** : Reference to original complaint/issue ID **severity** : Warning severity: info, warning, critical **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/sendsystemmessage** ```js axios({ method: 'POST', url: '/v1/sendsystemmessage', data: { targetUserId:"ID", targetUserRole:"String", messageContent:"Text", resolutionType:"String", complaintId:"ID", severity:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "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 messages in a chat hub room. Accessible by admins and room participants. **Rest Route** The `listChatMessages` API REST controller can be triggered via the following route: `/v1/v1/chat-messages` **Rest Request Parameters** **Filter Parameters** The `listChatMessages` api supports 9 optional filter parameters for filtering list results: **roomId** (`ID`): Reference to the room this message belongs to - Single: `?roomId=` - Multiple: `?roomId=&roomId=` - Null: `?roomId=null` **senderId** (`ID`): Reference to the user who sent this message - Single: `?senderId=` - Multiple: `?senderId=&senderId=` - Null: `?senderId=null` **senderName** (`String`): Display name of the sender (denormalized from user profile at send time) - Single (partial match, case-insensitive): `?senderName=` - Multiple: `?senderName=&senderName=` - Null: `?senderName=null` **senderAvatar** (`String`): Avatar URL of the sender (denormalized from user profile at send time) - Single (partial match, case-insensitive): `?senderAvatar=` - Multiple: `?senderAvatar=&senderAvatar=` - Null: `?senderAvatar=null` **messageType** (`Enum`): Content type discriminator for this message - Single: `?messageType=` (case-insensitive) - Multiple: `?messageType=&messageType=` - Null: `?messageType=null` **content** (`Object`): Type-specific content payload (structure depends on messageType) - Single: `?content=` - Multiple: `?content=&content=` - Null: `?content=null` **timestamp** (`String`): Message creation time - Single (partial match, case-insensitive): `?timestamp=` - Multiple: `?timestamp=×tamp=` - Null: `?timestamp=null` **status** (`Enum`): Message moderation status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **replyTo** (`Object`): Reply thread reference { id, preview } - Single: `?replyTo=` - Multiple: `?replyTo=&replyTo=` - Null: `?replyTo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages** ```js axios({ method: 'GET', url: '/v1/v1/chat-messages', data: { }, params: { // Filter parameters (see Filter Parameters section above) // roomId: '' // Filter by roomId // senderId: '' // Filter by senderId // senderName: '' // Filter by senderName // senderAvatar: '' // Filter by senderAvatar // messageType: '' // Filter by messageType // content: '' // Filter by content // timestamp: '' // Filter by timestamp // status: '' // Filter by status // replyTo: '' // Filter by replyTo } }); ``` **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", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `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 single chat hub message by ID. **Rest Route** The `getChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `getChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to query the required data object. **id** : This parameter will be used to select the data object that is queried **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages/:id** ```js axios({ method: 'GET', url: `/v1/v1/chat-messages/${id}`, 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", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Chatmessage` API **[Default delete API]** — This is the designated default `delete` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a chat hub message. Admins can delete any message; users can delete their own. **Rest Route** The `deleteChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `deleteChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to select the required data object that will be deleted **id** : This parameter will be used to select the data object that want to be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/v1/chat-messages/:id** ```js axios({ method: 'DELETE', url: `/v1/v1/chat-messages/${id}`, 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": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Chatmessage` API **[Default update API]** — This is the designated default `update` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a chat hub message content. Only the message sender or admins can edit. **Rest Route** The `updateChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `updateChatMessage` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | content | Object | false | request.body?.["content"] | | status | Enum | false | request.body?.["status"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to select the required data object that will be updated **content** : Type-specific content payload (structure depends on messageType) **status** : Message moderation status **id** : This parameter will be used to select the data object that want to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/v1/chat-messages/:id** ```js axios({ method: 'PATCH', url: `/v1/v1/chat-messages/${id}`, data: { content:"Object", status:"Enum", }, 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": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## Messaging Service Realtime Hubs # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 13 - Messaging Service Realtime Hubs** This document is a part of a REST API guide for the tutorhub project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document provides the **Realtime Hub** integration guide for the **Messaging** service. Realtime Hubs use **Socket.IO** for bidirectional communication between clients and the server, enabling features like chat rooms, live collaboration, game lobbies, and dashboards. ## Connection Setup ### Service URLs The Socket.IO server runs on the same host as the REST API for the **messaging** service: * **Preview:** `https://tutorhub.prw.mindbricks.com/messaging-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/messaging-api` * **Production:** `https://tutorhub.mindbricks.co/messaging-api` ### Authentication Every Socket.IO connection **must** include the user's access token and the correct `path` for the reverse proxy: ```js import { io } from "socket.io-client"; const socket = io("{baseUrl}/hub/{hubName}", { path: "/messaging-api/socket.io/", // HTTP transport path (reverse proxy) auth: { token: accessToken }, // Bearer token from login transports: ["websocket", "polling"], // prefer websocket }); ``` Where `{baseUrl}` is the service base URL (e.g., `https://tutorhub.mindbricks.co/messaging-api`). **How Socket.IO works behind a reverse proxy:** - The URL passed to `io()` is `{baseUrl}/hub/{hubName}` where `{baseUrl}` already includes the service prefix (e.g., `/messaging-api`). Socket.IO extracts the full path after the host as the **namespace** (`/messaging-api/hub/{hubName}`). Namespaces are logical channels negotiated inside the Socket.IO protocol — the reverse proxy does not affect them. - The `path` option (`/messaging-api/socket.io/`) is the **HTTP endpoint** the browser sends for the Socket.IO handshake, polling, and WebSocket upgrade. The reverse proxy routes this to the correct service and strips the prefix, so the server internally matches on the default `/socket.io/` path. The server validates the token and resolves the user session before allowing any interaction. If the token is invalid or missing, the connection is rejected with an `"Authentication required"` or `"Invalid token"` error. ### Connection Lifecycle ``` connect → authenticate → join rooms → send/receive → leave rooms → disconnect ``` Listen for connection events: ```js socket.on("connect", () => { console.log("Connected to hub", socket.id); }); socket.on("connect_error", (err) => { console.error("Connection failed:", err.message); // Handle re-auth if token expired }); socket.on("disconnect", (reason) => { console.log("Disconnected:", reason); }); ``` ## Protocol Reference All hub events use the `hub:` prefix. Below is the complete protocol that applies to every hub in this service. ### Room Management | Event | Direction | Payload | Description | |-------|-----------|---------|-------------| | `hub:join` | Client → Server | `{ roomId, meta? }` | Join a room. `meta` is optional user metadata broadcast to others. | | `hub:joined` | Server → Client | `{ roomId, hubRole, userInfo }` | Confirmation that the client successfully joined. `userInfo` contains `{ fullname, avatar }`. | | `hub:leave` | Client → Server | `{ roomId }` | Leave a room. | | `hub:error` | Server → Client | `{ roomId?, error }` | Error response for any failed operation. | | `hub:presence` | Server → Room | `{ event, roomId, user }` | Broadcast when a user joins or leaves. `event` is `"joined"` or `"left"`. `user` includes `{ id, fullname, avatar, hubRole }`. | **Join a room:** ```js socket.emit("hub:join", { roomId: "room-abc-123" }); socket.on("hub:joined", ({ roomId, hubRole, userInfo }) => { console.log("Joined room", roomId, "as", hubRole); // userInfo = { fullname: "John Doe", avatar: "https://..." } }); socket.on("hub:presence", ({ event, roomId, user }) => { // user = { id, fullname, avatar, hubRole } if (event === "joined") showUserJoined(roomId, user); if (event === "left") showUserLeft(roomId, user); }); socket.on("hub:error", ({ error }) => { console.error("Error:", error); }); ``` ### Sending Messages | Event | Direction | Payload | |-------|-----------|---------| | `hub:send` | Client → Server | `{ roomId, messageType, content, replyTo?, forwarded? }` | | `hub:messageArrived` | Server → Room | `{ roomId, sender, message }` — `sender` includes `{ id, fullname, avatar }` | **Send a message:** ```js socket.emit("hub:send", { roomId: "room-abc-123", messageType: "text", content: { body: "Hello everyone!" } }); ``` **Receive messages:** ```js socket.on("hub:messageArrived", ({ roomId, sender, message }) => { // sender = { id, fullname, avatar } // message = { id, messageType, content, timestamp, senderName, senderAvatar, ... } addMessageToUI(roomId, sender, message); }); ``` ### History When joining a room (if history is enabled), the server **automatically** sends the most recent messages right after the `hub:joined` event. Each message in the history array includes `senderName` and `senderAvatar` fields, so the frontend can render user display names and avatars without additional lookups. | Event | Direction | Payload | |-------|-----------|---------| | `hub:history` | Server → Client | `{ roomId, messages[] }` | **Automatic history on join:** ```js socket.on("hub:history", ({ roomId, messages }) => { // messages are ordered newest-first, each has: id, roomId, senderId, // senderName, senderAvatar, messageType, content, timestamp, status renderMessageHistory(roomId, messages); }); ``` **Paginated history via REST (for "load more" / scroll-up):** For older messages beyond the initial batch, use the REST endpoint: ``` GET /{hubKebabName}/{roomId}/messages?limit=50&offset=50 Authorization: Bearer {accessToken} ``` Response: `{ data: Message[], pagination: { total: number } }` Each message in the REST response also contains `senderName` and `senderAvatar`. ### Custom Events | Event | Direction | Payload | |-------|-----------|---------| | `hub:event` | Client → Server | `{ roomId, event, data }` | | `hub:{eventName}` | Server → Room | `{ roomId, userId, ...data }` | ```js // Emit a custom event socket.emit("hub:event", { roomId: "room-abc-123", event: "customAction", data: { key: "value" } }); // Listen for custom events socket.on("hub:customAction", ({ roomId, userId, ...data }) => { handleCustomEvent(roomId, userId, data); }); ``` --- ## Hub Definitions ## Hub: `chat` **Namespace:** `/messaging-api/hub/chat` **Description:** Real-time chat hub for TutorHub. Supports three channel types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings to students), adminTutor (bidirectional admin-tutor communication). Authorization is role-aware: students in adminStudent rooms get viewer role (read-only). ### Connection ```js const chatSocket = io("{baseUrl}/messaging-api/hub/chat", { path: "/messaging-api/socket.io/", auth: { token: accessToken }, transports: ["websocket", "polling"] }); ``` ### Room Settings | Setting | Value | |---------|-------| | Room DataObject | `conversation` | | Room Eligibility | `conversation.status == 'active'` | | Absolute Roles (bypass auth) | `superAdmin` | **Authorization Sources** (checked in order, first match wins): | # | Name | Source Object | User Field | Room Field | Hub Role | Condition | |---|------|-----------|------------|------------|----------|-----------| | 1 | `participantACheck` | `conversation` | `participantA` | `id` | `member` | — | | 2 | `participantBAdminStudent` | `conversation` | `participantB` | `id` | `viewer` | conversation.conversationType == 'adminStudent' | | 3 | `participantBCheck` | `conversation` | `participantB` | `id` | `member` | conversation.conversationType != 'adminStudent' | ### Hub Roles | Role | Read | Send | Allowed Types | Moderated | Moderate | Delete Any | Manage Room | |------|------|------|---------------|-----------|----------|------------|-------------| | `member` | Yes | Yes | all | No | No | No | No | | `viewer` | Yes | No | all | No | No | No | No | Users with `absoluteRoles` get a built-in **system** role with all permissions. **Room Eligibility Check:** Before joining, you can check if a room supports real-time features: ``` GET /chat/{roomId}/eligible ``` Response: `{ "success": true, "eligible": true/false }` Use this to conditionally show/hide the chat UI. ### Message Types Messages are stored in the **`chatMessage`** DataObject with the following structure: | Field | Type | Description | |-------|------|-------------| | `id` | ID | Primary key | | `roomId` | ID | Reference to the room | | `senderId` | ID | Reference to the sending user | | `senderName` | String | Display name of the sender (denormalized at send time) | | `senderAvatar` | String | Avatar URL of the sender (denormalized at send time) | | `messageType` | Enum | One of: `text`, `image`, `document`, `system`, `warning` | | `content` | JSON | Type-specific payload (see below) | | `timestamp` | DateTime | Message creation time | | `replyTo` | JSON | Reply thread reference `{ id, preview }` | #### Built-in Message Types Each message type requires specific fields in the `content` object: **`text`** | Field | Type | Required | |-------|------|----------| | `body` | Text | Yes | ```js socket.emit("hub:send", { roomId, messageType: "text", content: { body: "..." } }); ``` **`image`** | Field | Type | Required | |-------|------|----------| | `mediaUrl` | String | Yes | | `thumbnail` | String | No | | `caption` | String | No | | `width` | Integer | No | | `height` | Integer | No | ```js socket.emit("hub:send", { roomId, messageType: "image", content: { mediaUrl: "..." } }); ``` **`document`** | Field | Type | Required | |-------|------|----------| | `mediaUrl` | String | Yes | | `fileName` | String | Yes | | `fileSize` | Integer | No | | `mimeType` | String | No | ```js socket.emit("hub:send", { roomId, messageType: "document", content: { mediaUrl: "...", fileName: "..." } }); ``` **`system`** | Field | Type | Required | |-------|------|----------| | `systemAction` | String | Yes | | `systemData` | JSON | No | ```js socket.emit("hub:send", { roomId, messageType: "system", content: { systemAction: "..." } }); ``` #### Custom Message Types **`warning`** — Admin warning message sent as part of moderation actions. Rendered with amber/yellow alert styling in the frontend. | Field | Type | Required | |-------|------|----------| | `body` | | Yes | | `resolutionType` | | No | | `complaintId` | | No | | `severity` | | Yes | ```js socket.emit("hub:send", { roomId, messageType: "warning", content: { body: "...", severity: "..." } }); ``` ### Cross-cutting Features **Reply to messages:** Include `replyTo` in the send payload: ```js socket.emit("hub:send", { roomId, messageType: "text", content: { body: "I agree!" }, replyTo: originalMessageId }); ``` ### Standard Events | Event | Client Emits | Server Broadcasts | |-------|-------------|-------------------| | Typing | `hub:event` with `event: "typing"` | `hub:typing` `{ roomId, userId }` | | Stop Typing | `hub:event` with `event: "stopTyping"` | `hub:stopTyping` `{ roomId, userId }` | | Read Receipt | `hub:event` with `event: "messageRead"` | `hub:messageRead` `{ roomId, userId, lastReadTimestamp }` | | Presence Online | _(automatic on connect)_ | `hub:online` `{ roomId, userId }` | | Presence Offline | _(automatic on disconnect)_ | `hub:offline` `{ roomId, userId }` | **Example — Typing indicator:** ```js // Start typing socket.emit("hub:event", { roomId, event: "typing" }); // Stop typing (call after a debounce timeout) socket.emit("hub:event", { roomId, event: "stopTyping" }); // Listen for others typing socket.on("hub:typing", ({ roomId, userId }) => { showTypingIndicator(roomId, userId); }); socket.on("hub:stopTyping", ({ roomId, userId }) => { hideTypingIndicator(roomId, userId); }); ``` **Example — Read receipts:** ```js // Mark messages as read socket.emit("hub:event", { roomId, event: "messageRead", data: { lastReadTimestamp: new Date().toISOString() } }); // Listen for read receipts socket.on("hub:messageRead", ({ roomId, userId, lastReadTimestamp }) => { updateReadStatus(roomId, userId, lastReadTimestamp); }); ``` ### Moderation Commands Users with `canModerate` permission can block, silence, and manage messages: **Block/Unblock a user:** ```js socket.emit("hub:block", { roomId, userId: targetUserId, reason: "Spam", duration: 3600 }); socket.emit("hub:unblock", { roomId, userId: targetUserId }); ``` **Silence/Unsilence a user:** ```js socket.emit("hub:silence", { roomId, userId: targetUserId, reason: "Off-topic", duration: 600 }); socket.emit("hub:unsilence", { roomId, userId: targetUserId }); ``` Duration is in seconds. `0` or omitted = permanent. **Listen for moderation actions on your user:** ```js socket.on("hub:blocked", ({ roomId, reason }) => { // You have been blocked — leave UI, show message }); socket.on("hub:unblocked", ({ roomId }) => { // Block lifted — you may rejoin the room }); socket.on("hub:silenced", ({ roomId, reason }) => { // You have been silenced — disable send button }); socket.on("hub:unsilenced", ({ roomId }) => { // Silence lifted — re-enable send button }); ``` ### REST API Endpoints In addition to Socket.IO, the hub exposes REST endpoints for message history and management: **Get message history:** ``` GET /chat/{roomId}/messages?limit=50&offset=0 ``` Response: ```json { "success": true, "data": [ /* message objects */ ], "pagination": { "limit": 50, "offset": 0, "total": 120 } } ``` **Send a message via REST:** ``` POST /chat/{roomId}/messages Content-Type: application/json Authorization: Bearer {accessToken} { "data": { "body": "Hello from REST" }, "replyTo": null } ``` Messages sent via REST are also broadcast to all connected Socket.IO clients in the room. **Delete a message:** ``` DELETE /chat/{roomId}/messages/{messageId} Authorization: Bearer {accessToken} ``` ### Guardrails | Limit | Value | |-------|-------| | Max users per room | 10 | | Max rooms per user | 100 | | Message rate limit | 30 msg/min | | Max message size | 65536 bytes | | Connection timeout | 300000 ms | | History on join | Last 50 messages | ## Frontend Integration Checklist 1. **Install socket.io-client:** `npm install socket.io-client` 2. **Create a connection manager** that handles connect/disconnect/reconnect with token refresh. 3. **Join rooms** after connection. Listen for `hub:joined` before sending messages. The `hub:joined` event includes the user's `hubRole` and `userInfo` (fullname, avatar). 4. **Render chat history** from the `hub:history` event that arrives automatically after joining. Each message includes `senderName` and `senderAvatar` for display. 5. **Handle `hub:error`** globally for all error responses. 6. **Use sender info** from `hub:messageArrived` events — the `sender` object includes `{ id, fullname, avatar }`. For history messages, use the stored `senderName` and `senderAvatar` fields. 7. **Parse `messageType`** to render different message bubbles (text, image, video, etc.). 8. **Use REST endpoints** for paginated history when scrolling up in a conversation (`GET /{hubKebabName}/{roomId}/messages?limit=50&offset=50`). 9. **Debounce typing indicators** — emit `typing` on keypress, `stopTyping` after 2–3 seconds of inactivity. 10. **Track read receipts** per room to show unread counts and read status. 11. **Handle presence** to show online/offline status. The `hub:presence` event includes `user.fullname` and `user.avatar` for display. 12. **Reconnect gracefully** — re-join rooms and fetch missed messages via REST on reconnect. ## Example: Full Chat Integration ```js import { io } from "socket.io-client"; class ChatHub { constructor(baseUrl, token) { this.socket = io(`${baseUrl}/messaging-api/hub/chat`, { path: "/messaging-api/socket.io/", auth: { token }, transports: ["websocket", "polling"] }); this.rooms = new Map(); this._setupListeners(); } _setupListeners() { this.socket.on("hub:joined", ({ roomId, hubRole, userInfo }) => { this.rooms.set(roomId, { joined: true, hubRole, userInfo, messages: [], members: new Map() }); }); this.socket.on("hub:history", ({ roomId, messages }) => { const room = this.rooms.get(roomId); if (room) room.messages = messages; // Each message has senderName and senderAvatar for display }); this.socket.on("hub:presence", ({ event, roomId, user }) => { const room = this.rooms.get(roomId); if (!room) return; if (event === "joined") { room.members.set(user.id, { fullname: user.fullname, avatar: user.avatar, hubRole: user.hubRole }); } else if (event === "left") { room.members.delete(user.id); } }); this.socket.on("hub:messageArrived", ({ roomId, sender, message }) => { // sender = { id, fullname, avatar } const room = this.rooms.get(roomId); if (room) room.messages.push(message); this.onNewMessage?.(roomId, sender, message); }); this.socket.on("hub:error", ({ error }) => { console.error("[ChatHub]", error); }); this.socket.on("hub:typing", ({ roomId, userId }) => { this.onTyping?.(roomId, userId, true); }); this.socket.on("hub:stopTyping", ({ roomId, userId }) => { this.onTyping?.(roomId, userId, false); }); this.socket.on("hub:online", ({ roomId, userId }) => { this.onPresence?.(userId, "online"); }); this.socket.on("hub:offline", ({ roomId, userId }) => { this.onPresence?.(userId, "offline"); }); } joinRoom(roomId) { this.socket.emit("hub:join", { roomId }); } leaveRoom(roomId) { this.socket.emit("hub:leave", { roomId }); this.rooms.delete(roomId); } sendMessage(roomId, messageType, content, options = {}) { this.socket.emit("hub:send", { roomId, messageType, content, ...options }); } sendTyping(roomId) { this.socket.emit("hub:event", { roomId, event: "typing" }); } sendStopTyping(roomId) { this.socket.emit("hub:event", { roomId, event: "stopTyping" }); } disconnect() { this.socket.disconnect(); } } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- ## AgentHub Service # **TUTORHUB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 14 - AgentHub Service** This document is a part of a REST API guide for the tutorhub 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://tutorhub.prw.mindbricks.com/agenthub-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/agenthub-api` * **Production:** `https://tutorhub.mindbricks.co/agenthub-api` ## Scope **AgentHub Service Description** AI Agent Hub AgentHub service provides apis and business logic for following data objects in tutorhub 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.52`** ## 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 'tutorhub-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://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.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 `tutorApplicationStatus` `certifications` `qualifications` `bio` `specializations` `applicationReviewNote` `applicationDocuments` `accountStatus` 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 `tutorhub-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. | | `tutorApplicationStatus` | String | No | - | | `certifications` | Text | No | Tutor applicant's professional certifications. | | `qualifications` | Text | No | Tutor applicant's educational qualifications. | | `bio` | Text | No | Short professional bio for the tutor applicant. | | `specializations` | String | No | Subject areas the tutor specializes in. | | `applicationReviewNote` | Text | No | - | | `applicationDocuments` | String | No | URLs of uploaded documents for tutor application. | | `accountStatus` | String | No | - | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `specializations` `applicationDocuments` 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 - **tutorApplicationStatus**: none - **accountStatus**: active ### 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` - **tutorApplicationStatus**: Will be created with value `none` - **accountStatus**: Will be created with value `active` ### 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` `tutorApplicationStatus` `certifications` `qualifications` `bio` `specializations` `applicationReviewNote` `applicationDocuments` `accountStatus` 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. - **tutorApplicationStatus**: [none, pending, approved, rejected] - **accountStatus**: [active, suspended, banned] ### Elastic Search Indexing `email` `fullname` `roleId` `emailVerified` `accountStatus` 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` `accountStatus` 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` 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` ## 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 ## tutorhub-auth-service **Version:** `1.0.52` 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 | tutorhub-access-token| | Cookie | tutorhub-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://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.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.* | | **tutorApplicationStatus** | String | | | ** | | **certifications** | Text | | | *Tutor applicant's professional certifications.* | | **qualifications** | Text | | | *Tutor applicant's educational qualifications.* | | **bio** | Text | | | *Short professional bio for the tutor applicant.* | | **specializations** | String | | | *Subject areas the tutor specializes in.* | | **applicationReviewNote** | Text | | | ** | | **applicationDocuments** | String | | | *URLs of uploaded documents for tutor application.* | | **accountStatus** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### tutorApplicationStatus Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **none** | `"none""` | 0 | | **pending** | `"pending""` | 1 | | **approved** | `"approved""` | 2 | | **rejected** | `"rejected""` | 3 | ##### accountStatus Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **suspended** | `"suspended""` | 1 | | **banned** | `"banned""` | 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **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 **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **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", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **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 **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **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", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 10 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"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | **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 **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **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", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", }, 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 3 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` **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 } }); ``` **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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 1 optional filter parameter 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` **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 } }); ``` **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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 10 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"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | **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. **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **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", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", }, 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Apply Astutor` API Authenticated user submits a tutor application. **API Frontend Description By The Backend Architect** Show a dedicated Apply as Tutor page for logged-in users. **Rest Route** The `applyAsTutor` API REST controller can be triggered via the following route: `/v1/applyastutor/:userId` **Rest Request Parameters** The `applyAsTutor` api has got 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **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 **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/applyastutor/:userId** ```js axios({ method: 'PATCH', url: `/v1/applyastutor/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Review Tutorapplication` API **Rest Route** The `reviewTutorApplication` API REST controller can be triggered via the following route: `/v1/reviewtutorapplication/:userId` **Rest Request Parameters** The `reviewTutorApplication` api has got 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **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 **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/reviewtutorapplication/:userId** ```js axios({ method: 'PATCH', url: `/v1/reviewtutorapplication/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 ## tutorhub-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**: `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent user-updated **Event topic**: `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent user-deleted **Event topic**: `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent userAvatarsFile-created **Event topic**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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-tutorhub_user-created` **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event user-updated **Event topic**: `elastic-index-tutorhub_user-created` **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event user-deleted **Event topic**: `elastic-index-tutorhub_user-deleted` **Event payload**: ```json {"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event user-extended **Event topic**: `elastic-index-tutorhub_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** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-created **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-deleted **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-archived **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event users-listed **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_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 users-searched **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_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 userrole-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpassword-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpasswordbyadmin-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event briefuser-retrived **Event topic** : `tutorhub-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** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event astutor-applyed **Event topic** : `tutorhub-auth-service-astutor-applyed` **Event payload**: The 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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorapplication-reviewed **Event topic** : `tutorhub-auth-service-tutorapplication-reviewed` **Event payload**: The 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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event useravatarsfile-retrived **Event topic** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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-tutorhub_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-tutorhub_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-tutorhub_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-tutorhub_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** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-created **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event user-deleted **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event profile-archived **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event users-listed **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_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 users-searched **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_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 userrole-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpassword-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event userpasswordbyadmin-updated **Event topic** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event briefuser-retrived **Event topic** : `tutorhub-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** : `tutorhub-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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event astutor-applyed **Event topic** : `tutorhub-auth-service-astutor-applyed` **Event payload**: The 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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorapplication-reviewed **Event topic** : `tutorhub-auth-service-tutorapplication-reviewed` **Event payload**: The 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","tutorApplicationStatus":"String","tutorApplicationStatus_idx":"Integer","certifications":"Text","qualifications":"Text","bio":"Text","specializations":"String","applicationReviewNote":"Text","applicationDocuments":"String","accountStatus":"String","accountStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event useravatarsfile-retrived **Event topic** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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 **tutorhub-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. | | `tutorApplicationStatus` | String | No | - | | `certifications` | Text | No | Tutor applicant's professional certifications. | | `qualifications` | Text | No | Tutor applicant's educational qualifications. | | `bio` | Text | No | Short professional bio for the tutor applicant. | | `specializations` | String | No | Subject areas the tutor specializes in. | | `applicationReviewNote` | Text | No | - | | `applicationDocuments` | String | No | URLs of uploaded documents for tutor application. | | `accountStatus` | String | No | - | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `specializations` `applicationDocuments` 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 - **tutorApplicationStatus**: none - **accountStatus**: active ### 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` - **tutorApplicationStatus**: Will be created with value `none` - **accountStatus**: Will be created with value `active` ### 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` `tutorApplicationStatus` `certifications` `qualifications` `bio` `specializations` `applicationReviewNote` `applicationDocuments` `accountStatus` 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. - **tutorApplicationStatus**: [none, pending, approved, rejected] - **accountStatus**: [active, suspended, banned] ### Elastic Search Indexing `email` `fullname` `roleId` `emailVerified` `accountStatus` 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` `accountStatus` 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` 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` --- ### Service Design Specification - Object Design for userAvatarsFile # Service Design Specification - Object Design for userAvatarsFile **tutorhub-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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `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 | | | | | | | | | | | | | `tutorApplicationStatus` | `String` | `No` | `-` | `body` | `tutorApplicationStatus` | | **Description:** | - | | | | | | | | | | | | | `certifications` | `Text` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor applicant's professional certifications. | | | | | | | | | | | | | `qualifications` | `Text` | `No` | `-` | `body` | `qualifications` | | **Description:** | Tutor applicant's educational qualifications. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Short professional bio for the tutor applicant. | | | | | | | | | | | | | `specializations` | `String` | `No` | `-` | `body` | `specializations` | | **Description:** | Subject areas the tutor specializes in. | | | | | | | | | | | | | `applicationReviewNote` | `Text` | `No` | `-` | `body` | `applicationReviewNote` | | **Description:** | - | | | | | | | | | | | | | `applicationDocuments` | `String` | `No` | `-` | `body` | `applicationDocuments` | | **Description:** | URLs of uploaded documents for tutor application. | | | | | | | | | | | | | `accountStatus` | `String` | `No` | `-` | `body` | `accountStatus` | | **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 `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, tutorApplicationStatus: this.tutorApplicationStatus, certifications: this.certifications, qualifications: this.qualifications, bio: this.bio, specializations: this.specializations ? this.specializations : ( this.specializations_remove ? sequelize.fn('array_remove', sequelize.col('specializations'), this.specializations_remove) : (this.specializations_append ? sequelize.fn('array_append', sequelize.col('specializations'), this.specializations_append) : undefined)) , applicationReviewNote: this.applicationReviewNote, applicationDocuments: this.applicationDocuments ? this.applicationDocuments : ( this.applicationDocuments_remove ? sequelize.fn('array_remove', sequelize.col('applicationDocuments'), this.applicationDocuments_remove) : (this.applicationDocuments_append ? sequelize.fn('array_append', sequelize.col('applicationDocuments'), this.applicationDocuments_append) : undefined)) , accountStatus: this.accountStatus, } ``` ## 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 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | ### 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", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `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 | | | | | | | | | | | | | `tutorApplicationStatus` | `String` | `No` | `-` | `body` | `tutorApplicationStatus` | | **Description:** | - | | | | | | | | | | | | | `certifications` | `Text` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor applicant's professional certifications. | | | | | | | | | | | | | `qualifications` | `Text` | `No` | `-` | `body` | `qualifications` | | **Description:** | Tutor applicant's educational qualifications. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Short professional bio for the tutor applicant. | | | | | | | | | | | | | `specializations` | `String` | `No` | `-` | `body` | `specializations` | | **Description:** | Subject areas the tutor specializes in. | | | | | | | | | | | | | `applicationReviewNote` | `Text` | `No` | `-` | `body` | `applicationReviewNote` | | **Description:** | - | | | | | | | | | | | | | `applicationDocuments` | `String` | `No` | `-` | `body` | `applicationDocuments` | | **Description:** | URLs of uploaded documents for tutor application. | | | | | | | | | | | | | `accountStatus` | `String` | `No` | `-` | `body` | `accountStatus` | | **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 `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, tutorApplicationStatus: this.tutorApplicationStatus, certifications: this.certifications, qualifications: this.qualifications, bio: this.bio, specializations: this.specializations ? this.specializations : ( this.specializations_remove ? sequelize.fn('array_remove', sequelize.col('specializations'), this.specializations_remove) : (this.specializations_append ? sequelize.fn('array_append', sequelize.col('specializations'), this.specializations_append) : undefined)) , applicationReviewNote: this.applicationReviewNote, applicationDocuments: this.applicationDocuments ? this.applicationDocuments : ( this.applicationDocuments_remove ? sequelize.fn('array_remove', sequelize.col('applicationDocuments'), this.applicationDocuments_remove) : (this.applicationDocuments_append ? sequelize.fn('array_append', sequelize.col('applicationDocuments'), this.applicationDocuments_append) : undefined)) , accountStatus: this.accountStatus, } ``` ## 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 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | ### 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", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `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 | | | | | | | | | | | | | `certifications` | `Text` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor applicant's professional certifications. | | | | | | | | | | | | | `qualifications` | `Text` | `No` | `-` | `body` | `qualifications` | | **Description:** | Tutor applicant's educational qualifications. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Short professional bio for the tutor applicant. | | | | | | | | | | | | | `specializations` | `String` | `No` | `-` | `body` | `specializations` | | **Description:** | Subject areas the tutor specializes in. | | | | | | | | | | | | | `applicationReviewNote` | `Text` | `No` | `-` | `body` | `applicationReviewNote` | | **Description:** | - | | | | | | | | | | | | | `applicationDocuments` | `String` | `No` | `-` | `body` | `applicationDocuments` | | **Description:** | URLs of uploaded documents for tutor application. | | | | | | | | | | | | ### 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, certifications: this.certifications, qualifications: this.qualifications, bio: this.bio, specializations: this.specializations, applicationReviewNote: this.applicationReviewNote, applicationDocuments: this.applicationDocuments, 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 10 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"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | ### 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", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"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": "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 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 `listUsers` api supports 3 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 ``` ### 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 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | 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. | ### 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 } }); ``` ### 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_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 - `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 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `keyword` | `String` | `Yes` | `-` | `query` | `keyword` | | **Description:** | - | | | | | | | | | | | | ### Filter Parameters The `searchUsers` api supports 1 optional filter parameter 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 ``` ### 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 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | roleId | String | No | A string value to represent the roleId of the user. | ### 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 } }); ``` ### 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_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 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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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 12 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. | | | | | | | | | | | | | `certifications` | `Text` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor applicant's professional certifications. | | | | | | | | | | | | | `qualifications` | `Text` | `No` | `-` | `body` | `qualifications` | | **Description:** | Tutor applicant's educational qualifications. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Short professional bio for the tutor applicant. | | | | | | | | | | | | | `specializations` | `String` | `No` | `-` | `body` | `specializations` | | **Description:** | Subject areas the tutor specializes in. | | | | | | | | | | | | | `applicationReviewNote` | `Text` | `No` | `-` | `body` | `applicationReviewNote` | | **Description:** | - | | | | | | | | | | | | | `applicationDocuments` | `String` | `No` | `-` | `body` | `applicationDocuments` | | **Description:** | URLs of uploaded documents for tutor application. | | | | | | | | | | | | ### 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, certifications: this.certifications, qualifications: this.qualifications, bio: this.bio, specializations: this.specializations, applicationReviewNote: this.applicationReviewNote, applicationDocuments: this.applicationDocuments, 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 10 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"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | ### 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", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"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": "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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Apply Astutor` # Business API Design Specification - `Apply Astutor` 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 `applyAsTutor` 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 `applyAsTutor` 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 Authenticated user submits a tutor application. ## API Frontend Description By The Backend Architect Show a dedicated Apply as Tutor page for logged-in 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** : `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 `astutor-applyed` 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 `applyAsTutor` Business API includes a REST controller that can be triggered via the following route: `/v1/applyastutor/: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 `applyAsTutor` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `applyAsTutor` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `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 | | | | | | | | | | | | | `tutorApplicationStatus` | `String` | `No` | `-` | `body` | `tutorApplicationStatus` | | **Description:** | - | | | | | | | | | | | | | `certifications` | `Text` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor applicant's professional certifications. | | | | | | | | | | | | | `qualifications` | `Text` | `No` | `-` | `body` | `qualifications` | | **Description:** | Tutor applicant's educational qualifications. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Short professional bio for the tutor applicant. | | | | | | | | | | | | | `specializations` | `String` | `No` | `-` | `body` | `specializations` | | **Description:** | Subject areas the tutor specializes in. | | | | | | | | | | | | | `applicationReviewNote` | `Text` | `No` | `-` | `body` | `applicationReviewNote` | | **Description:** | - | | | | | | | | | | | | | `applicationDocuments` | `String` | `No` | `-` | `body` | `applicationDocuments` | | **Description:** | URLs of uploaded documents for tutor application. | | | | | | | | | | | | | `accountStatus` | `String` | `No` | `-` | `body` | `accountStatus` | | **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 `applyAsTutor` 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[14].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 { tutorApplicationStatus: runMScript(() => ("pending"), {"path":"services[0].businessLogic[14].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 { fullname: this.fullname, avatar: this.avatar, tutorApplicationStatus: runMScript(() => ("pending"), {"path":"services[0].businessLogic[14].dataClause.customData[0].value"}), certifications: this.certifications, qualifications: this.qualifications, bio: this.bio, specializations: this.specializations ? this.specializations : ( this.specializations_remove ? sequelize.fn('array_remove', sequelize.col('specializations'), this.specializations_remove) : (this.specializations_append ? sequelize.fn('array_append', sequelize.col('specializations'), this.specializations_append) : undefined)) , applicationReviewNote: this.applicationReviewNote, applicationDocuments: this.applicationDocuments ? this.applicationDocuments : ( this.applicationDocuments_remove ? sequelize.fn('array_remove', sequelize.col('applicationDocuments'), this.applicationDocuments_remove) : (this.applicationDocuments_append ? sequelize.fn('array_append', sequelize.col('applicationDocuments'), this.applicationDocuments_append) : undefined)) , accountStatus: this.accountStatus, } ``` ## 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 `applyAsTutor` api has got 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/applyastutor/:userId** ```js axios({ method: 'PATCH', url: `/v1/applyastutor/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Review Tutorapplication` # Business API Design Specification - `Review Tutorapplication` 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 `reviewTutorApplication` 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 `reviewTutorApplication` 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 ## 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 `tutorapplication-reviewed` 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 `reviewTutorApplication` Business API includes a REST controller that can be triggered via the following route: `/v1/reviewtutorapplication/: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 `reviewTutorApplication` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `reviewTutorApplication` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `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 | | | | | | | | | | | | | `tutorApplicationStatus` | `String` | `No` | `-` | `body` | `tutorApplicationStatus` | | **Description:** | - | | | | | | | | | | | | | `certifications` | `Text` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor applicant's professional certifications. | | | | | | | | | | | | | `qualifications` | `Text` | `No` | `-` | `body` | `qualifications` | | **Description:** | Tutor applicant's educational qualifications. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Short professional bio for the tutor applicant. | | | | | | | | | | | | | `specializations` | `String` | `No` | `-` | `body` | `specializations` | | **Description:** | Subject areas the tutor specializes in. | | | | | | | | | | | | | `applicationReviewNote` | `Text` | `No` | `-` | `body` | `applicationReviewNote` | | **Description:** | - | | | | | | | | | | | | | `applicationDocuments` | `String` | `No` | `-` | `body` | `applicationDocuments` | | **Description:** | URLs of uploaded documents for tutor application. | | | | | | | | | | | | | `accountStatus` | `String` | `No` | `-` | `body` | `accountStatus` | | **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 `reviewTutorApplication` 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[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** ```js { roleId: runMScript(() => (this.tutorApplicationStatus === 'approved' ? 'tutor' : 'student'), {"path":"services[0].businessLogic[15].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 { fullname: this.fullname, avatar: this.avatar, tutorApplicationStatus: this.tutorApplicationStatus, certifications: this.certifications, qualifications: this.qualifications, bio: this.bio, specializations: this.specializations ? this.specializations : ( this.specializations_remove ? sequelize.fn('array_remove', sequelize.col('specializations'), this.specializations_remove) : (this.specializations_append ? sequelize.fn('array_append', sequelize.col('specializations'), this.specializations_append) : undefined)) , applicationReviewNote: this.applicationReviewNote, applicationDocuments: this.applicationDocuments ? this.applicationDocuments : ( this.applicationDocuments_remove ? sequelize.fn('array_remove', sequelize.col('applicationDocuments'), this.applicationDocuments_remove) : (this.applicationDocuments_append ? sequelize.fn('array_append', sequelize.col('applicationDocuments'), this.applicationDocuments_append) : undefined)) , accountStatus: this.accountStatus, // roleId parameter is closed to update by client request // include it in data clause unless you are sure roleId: runMScript(() => (this.tutorApplicationStatus === 'approved' ? 'tutor' : 'student'), {"path":"services[0].businessLogic[15].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] Action : createProfileOnApproval **Action Type**: `InterserviceCallAction` ```js class Api { async createProfileOnApproval() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["tutorId"] = runMScript(() => this.id, { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[0].value", }); bodyParams["bio"] = runMScript(() => this.bio, { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[1].value", }); bodyParams["experience"] = runMScript(() => this.qualifications, { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[2].value", }); bodyParams["certifications"] = runMScript( () => (this.certifications ? [this.certifications] : []), { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[3].value", }, ); bodyParams["subjects"] = runMScript(() => this.specializations || [], { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[4].value", }); bodyParams["profileStatus"] = runMScript(() => "approved", { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[5].value", }); bodyParams["displayName"] = runMScript(() => this.fullname, { path: "services[0].businessLogic[15].actions.interserviceCallActions[0].apiParameters[6].value", }); const resp = await InterService.callTutorCatalogCreateTutorProfile({ body: bodyParams, }); const _respData = resp?.content ?? resp; return _respData?.id; } } ``` --- ### [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 `reviewTutorApplication` api has got 11 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"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/reviewtutorapplication/:userId** ```js axios({ method: 'PATCH', url: `/v1/reviewtutorapplication/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"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", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "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[16].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[18].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.* --- # TutorCatalog Service ## Service Design Specification # Service Design Specification **tutorhub-tutorcatalog-service** documentation **Version:** `1.0.45` ## Scope This document provides a structured architectural overview of the `tutorCatalog` 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. ## `TutorCatalog` Service Settings Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. ### Service Overview This service is configured to listen for HTTP requests on port `3000`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-tutorcatalog-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/tutorcatalog-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/tutorcatalog-api` * **Production:** `https://tutorhub.mindbricks.co/tutorcatalog-api` ### Authentication & Security - **Login Required**: No This service does not require user authentication for access. It is designed to be publicly accessible, allowing anonymous users to interact with its endpoints. However, certain CRUD routes may still require login based on their specific configurations. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-tutorcatalog-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 | |-------------|-------------|---------------| | `tutorProfile` | Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. | accessPublic | | `coursePack` | Publicly listed course pack/structured course offered by a tutor. | accessPrivate | | `courseMaterial` | Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. | accessPrivate | | `courseCategory` | Represents a course subject/category; used for filtering and navigation. Admin-maintained. | accessPublic | ## tutorProfile Data Object ### Object Overview **Description:** Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. 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:** accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `tutorId` | ID | Yes | - | | `certifications` | String | No | Tutor's certifications (list of certificates, degrees, etc.). | | `experience` | Text | No | Brief experience summary or bio. | | `subjects` | String | No | Areas of expertise/subjects offered for teaching. | | `bio` | Text | No | Optional full-length bio/description. | | `profilePhoto` | String | No | Public profile photo URL (may be external or uploaded). | | `profileStatus` | Enum | Yes | - | | `displayName` | String | No | Tutor's display name, copied from auth user fullname at profile creation. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `certifications` `subjects` 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. - **tutorId**: '00000000-0000-0000-0000-000000000000' - **profileStatus**: pending ### Auto Update Properties `tutorId` `certifications` `experience` `subjects` `bio` `profilePhoto` `profileStatus` `displayName` 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. - **profileStatus**: [pending, approved, rejected] ### Elastic Search Indexing `tutorId` `certifications` `experience` `subjects` `bio` `profilePhoto` `profileStatus` `displayName` 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 `tutorId` `profileStatus` 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 `tutorId` 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 `tutorId` 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 `tutorId` 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. - **tutorId**: 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 `tutorId` `profileStatus` 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. - **tutorId**: ID has a filter named `tutorId` - **profileStatus**: Enum has a filter named `profileStatus` ## coursePack Data Object ### Object Overview **Description:** Publicly listed course pack/structured course offered by a tutor. 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 - **coursePackByTutorAndTitle**: [tutorProfileId, title] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema **Display Label Property:** `title` — 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 | |----------|------|----------|-------------| | `tutorProfileId` | ID | Yes | - | | `title` | String | Yes | - | | `description` | Text | No | - | | `price` | Double | Yes | - | | `category` | String | Yes | - | | `schedulingType` | Enum | Yes | - | | `minWeeklyClasses` | Integer | No | - | | `preliminaryMeetingRequired` | Boolean | Yes | - | | `isPublished` | Boolean | Yes | - | | `maxDailyLessons` | Integer | No | - | | `requiredClassesCount` | Integer | No | - | | `moderationStatus` | Enum | No | Content moderation status. | | `moderationNote` | String | No | Admin note for flagged/removed course packs. | | `maxPeriodValue` | Integer | No | Maximum time period value for strict scheduling (e.g. 3 for 3 months) | | `maxPeriodUnit` | Enum | No | Time unit for maxPeriodValue in strict scheduling | * 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. - **tutorProfileId**: '00000000-0000-0000-0000-000000000000' - **title**: 'default' - **price**: 0.0 - **category**: 'default' - **schedulingType**: flexible - **isPublished**: true - **moderationStatus**: approved ### 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. - **moderationStatus**: Will be created with value `approved` ### Auto Update Properties `tutorProfileId` `title` `description` `price` `category` `schedulingType` `minWeeklyClasses` `preliminaryMeetingRequired` `isPublished` `maxDailyLessons` `requiredClassesCount` `moderationStatus` `moderationNote` `maxPeriodValue` `maxPeriodUnit` 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. - **schedulingType**: [flexible, strict] - **moderationStatus**: [approved, flagged, removed] - **maxPeriodUnit**: [weeks, months] ### Elastic Search Indexing `tutorProfileId` `title` `description` `price` `category` `schedulingType` `minWeeklyClasses` `preliminaryMeetingRequired` `isPublished` `maxDailyLessons` `requiredClassesCount` `moderationStatus` `maxPeriodValue` `maxPeriodUnit` 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 `tutorProfileId` `title` `category` `isPublished` `moderationStatus` 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 `tutorProfileId` 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 `tutorProfileId` `category` 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. - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **category**: String Relation to `courseCategory`.name 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: No ### Filter Properties `tutorProfileId` `title` `category` `schedulingType` `isPublished` `moderationStatus` 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. - **tutorProfileId**: ID has a filter named `tutorProfileId` - **title**: String has a filter named `courseTitle` - **category**: String has a filter named `category` - **schedulingType**: Enum has a filter named `scheduling` - **isPublished**: Boolean has a filter named `published` - **moderationStatus**: Enum has a filter named `moderationStatus` ## courseMaterial Data Object ### Object Overview **Description:** Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. 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 - **materialPerCourseTitle**: [coursePackId, title] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema **Display Label Property:** `title` — 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 | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to coursePack. | | `fileUrl` | String | Yes | URL for file/video/document. For downloads or video links (protected). | | `fileType` | Enum | Yes | Type: file, video, document, externalLink. | | `title` | String | Yes | Material title (unique per pack). | | `description` | Text | No | Additional details about the material resource. | | `linkUrl` | String | No | Optional URL for external resource (if fileType = externalLink). | * 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. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **fileUrl**: 'default' - **fileType**: "file" - **title**: 'default' ### Constant Properties `coursePackId` 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 `fileUrl` `fileType` `title` `description` `linkUrl` 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. - **fileType**: [file, video, document, externalLink] ### Elastic Search Indexing `coursePackId` `fileType` `title` `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 `coursePackId` `title` 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 `coursePackId` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Relation Properties `coursePackId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Filter Properties `fileType` 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. - **fileType**: Enum has a filter named `type` ## courseCategory Data Object ### Object Overview **Description:** Represents a course subject/category; used for filtering and navigation. Admin-maintained. 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:** accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **uniqueCategoryName**: [name] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema **Display Label Property:** `name` — 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 | |----------|------|----------|-------------| | `name` | String | Yes | Unique category/subject name. | | `description` | Text | No | Category description. | | `icon` | String | No | Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) | * 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. - **name**: 'default' - **icon**: 📚 ### Auto Update Properties `name` `description` `icon` 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 `name` `description` `icon` 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 `name` `icon` 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 `name` 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 `name` 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 `name` 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. - **name**: String has a filter named `name` ## Business Logic tutorCatalog has got 20 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Create Tutorprofile](/document/businessLogic/createtutorprofile) * [Update Tutorprofile](/document/businessLogic/updatetutorprofile) * [Get Tutorprofile](/document/businessLogic/gettutorprofile) * [List Tutorprofiles](/document/businessLogic/listtutorprofiles) * [Create Coursepack](/document/businessLogic/createcoursepack) * [Update Coursepack](/document/businessLogic/updatecoursepack) * [Delete Coursepack](/document/businessLogic/deletecoursepack) * [Get Coursepack](/document/businessLogic/getcoursepack) * [List Coursepacks](/document/businessLogic/listcoursepacks) * [Create Coursematerial](/document/businessLogic/createcoursematerial) * [Update Coursematerial](/document/businessLogic/updatecoursematerial) * [Delete Coursematerial](/document/businessLogic/deletecoursematerial) * [Get Coursematerial](/document/businessLogic/getcoursematerial) * [List Coursematerials](/document/businessLogic/listcoursematerials) * [Create Coursecategory](/document/businessLogic/createcoursecategory) * [Update Coursecategory](/document/businessLogic/updatecoursecategory) * [Delete Coursecategory](/document/businessLogic/deletecoursecategory) * [Get Coursecategory](/document/businessLogic/getcoursecategory) * [List Coursecategories](/document/businessLogic/listcoursecategories) * [On Tutorapplicationreviewed](/document/businessLogic/ontutorapplicationreviewed) ## Service Library ### Functions #### getTutorProfileIdsBySessionUserId.js ```js module.exports = async function getTutorProfileIdsBySessionUserId(userId) { if (!userId) return []; const db = require("dbLayer"); const items = await db.getTutorProfileListByMQuery({ tutorId: userId, isActive: true }); return items.map(i => i.id); } ``` #### getCoursePackIdsBySessionUserId.js ```js module.exports = async function getCoursePackIdsBySessionUserId(userId) { if (!userId) return []; const tutorProfileIds = await LIB.getTutorProfileIdsBySessionUserId(userId); if (!tutorProfileIds.length) return []; const db = require("dbLayer"); const packs = await db.getCoursePackListByMQuery({ tutorProfileId: { $in: tutorProfileIds }, isActive: true }); return packs.map(p => p.id); } ``` #### isMaterialViewAllowedBySession.js ```js module.exports = async function isMaterialViewAllowedBySession(courseMaterialId, userId, roleId) { if (!userId || !courseMaterialId) return false; if (roleId === "admin") return true; const MODELS = require("models"); const cm = await MODELS.CourseMaterial.findOne({ where: { id: courseMaterialId, isActive: true } }); if (!cm) return false; const pack = await MODELS.CoursePack.findOne({ where: { id: cm.coursePackId, isActive: true } }); if (!pack) return false; if (roleId === "tutor") { const tprofiles = await MODELS.TutorProfile.findAll({ where: { tutorId: userId, isActive: true } }); if (tprofiles.some(tpf => tpf.id === pack.tutorProfileId)) return true; } if (roleId === "student") { const { fetchRemoteListByMQuery } = require("serviceCommon"); const enrolls = await fetchRemoteListByMQuery("enrollmentManagement:enrollment", { studentId: userId, coursePackId: pack.id, isActive: true, enrollmentStatus: "active" }, 0, 1); if (enrolls && enrolls.length > 0) return true; } return false; } ``` #### getAllowedMaterialWhereClause.js ```js module.exports = async function getAllowedMaterialWhereClause(userId, roleId) { if (!userId) return { id: null }; if (roleId === "admin") return {}; const db = require("dbLayer"); if (roleId === "tutor") { const tprofiles = await db.getTutorProfileListByMQuery({ tutorId: userId, isActive: true }); if (!tprofiles.length) return { id: null }; const packs = await db.getCoursePackListByMQuery({ tutorProfileId: { $in: tprofiles.map(p => p.id) }, isActive: true }); const accessiblePackIds = packs.map(p => p.id); if (!accessiblePackIds.length) return { id: null }; return { coursePackId: { $in: accessiblePackIds } }; } if (roleId === "student") { const { fetchRemoteListByMQuery } = require("serviceCommon"); const enrolls = await fetchRemoteListByMQuery("enrollmentManagement:enrollment", { studentId: userId, isActive: true, enrollmentStatus: "active" }, 0, 100); const enrolledPackIds = enrolls ? enrolls.map(e => e.coursePackId) : []; if (!enrolledPackIds.length) return { id: null }; return { coursePackId: { $in: enrolledPackIds } }; } return { id: null }; } ``` #### checkCoursePackActiveEnrollments.js ```js module.exports = async function checkCoursePackActiveEnrollments(coursePackId) { if (!coursePackId) return { hasActiveEnrollments: false, count: 0, enrollments: [] }; try { // Use interservice HTTP call to enrollmentManagement's internal fetch endpoint // This reads from the DB (source of truth), not ES which may be stale const axios = require('axios'); const { getServiceSecret } = require('common'); // In preview, all services share the same base host with different routes const baseUrl = process.env.ENROLLMENTMANAGEMENT_API_URL || (process.env.PREVIEW_BASE_URL ? process.env.PREVIEW_BASE_URL + '/enrollmentmanagement-api' : null); // Fallback: use the _fetchList internal endpoint via M2M or query ES if (!baseUrl) { // Try ES as fallback const { elasticClient } = require('common'); const res = await elasticClient.search({ index: 'tutorhub_enrollment', body: { query: { bool: { must: [ { term: { coursePackId: coursePackId } }, { term: { enrollmentStatus: 'active' } }, { term: { isActive: true } } ] } }, size: 100 } }); const enrollments = res.hits.hits.map(h => h._source); return { hasActiveEnrollments: enrollments.length > 0, count: enrollments.length, enrollments }; } const serviceSecret = getServiceSecret ? getServiceSecret() : process.env.SERVICE_SECRET_KEY; const url = `${baseUrl}/m2m/getEnrollmentListByMQuery`; const response = await axios.post(url, { query: { coursePackId, enrollmentStatus: 'active', isActive: true } }, { headers: { 'Content-Type': 'application/json', ...(serviceSecret ? { 'x-service-secret': serviceSecret } : {}) }, timeout: 10000 }); const enrollments = response.data || []; return { hasActiveEnrollments: enrollments.length > 0, count: enrollments.length, enrollments }; } catch (err) { console.log('ERROR in checkCoursePackActiveEnrollments:', err.message); // FAIL SAFE: if we can't check, assume there ARE enrollments to prevent accidental deletion return { hasActiveEnrollments: true, count: -1, enrollments: [], error: err.message }; } } ``` #### triggerAdminCourseRemovalCascade.js ```js module.exports = async function triggerAdminCourseRemovalCascade(coursePackId, removalReason, enrollmentCheck, session) { const { fetchRemoteListByMQuery, callRemoteApi } = require('serviceCommon'); const { elasticClient } = require('common'); if (!enrollmentCheck || !enrollmentCheck.hasActiveEnrollments) { return { processed: 0, total: 0, refunds: [] }; } const enrollments = enrollmentCheck.enrollments || []; const results = { processed: 0, total: enrollments.length, refunds: [], errors: [] }; for (const enrollment of enrollments) { try { // Fetch lesson slots to calculate completion percentage const slotIds = enrollment.lessonSlotIds || []; let completedCount = 0; let totalSlots = slotIds.length; if (totalSlots > 0) { try { const slotsRes = await elasticClient.search({ index: 'tutorhub_lessonslot', body: { query: { terms: { id: slotIds } }, _source: ['id', 'status'], size: 500 } }); const slots = slotsRes.hits.hits.map(h => h._source); completedCount = slots.filter(s => s.status === 'completed').length; } catch (esErr) { console.log('Warning: ES slot lookup failed, assuming 0 completed:', esErr.message); } } // Calculate pro-rata refund amount const completionRatio = totalSlots > 0 ? completedCount / totalSlots : 0; let refundAmount = 0; let refundNote = ''; if (completionRatio === 0) { refundAmount = enrollment.totalAmount; refundNote = 'Full refund - no lessons completed'; } else if (completionRatio <= 0.5) { const unusedSlots = totalSlots - completedCount; refundAmount = Math.round((unusedSlots / totalSlots) * enrollment.totalAmount * 100) / 100; refundNote = `Pro-rata refund: ${completedCount}/${totalSlots} lessons completed, refunding ${unusedSlots} unused lessons`; } else { refundAmount = 0; refundNote = `No refund: ${completedCount}/${totalSlots} lessons completed (over 50%)`; } // Fetch student data for email notifications let studentData = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) studentData = studentRes.hits.hits[0]._source; } catch (e) { console.log('Warning: student lookup failed:', e.message); } if (refundAmount > 0) { try { await callRemoteApi('enrollmentManagement', 'adminRefundEnrollment', { enrollmentId: enrollment.id, reason: `Course removed by admin. Reason: ${removalReason || 'No reason provided'}. ${refundNote}` }, session); } catch (refundErr) { console.log('Warning: adminRefundEnrollment failed for', enrollment.id, ':', refundErr.message); results.errors.push({ enrollmentId: enrollment.id, error: refundErr.message }); } } else { try { await callRemoteApi('enrollmentManagement', 'cancelEnrollment', { enrollmentId: enrollment.id, reason: `Course removed by admin. Reason: ${removalReason || 'No reason provided'}. ${refundNote}` }, session); } catch (cancelErr) { console.log('Warning: cancelEnrollment failed for', enrollment.id, ':', cancelErr.message); results.errors.push({ enrollmentId: enrollment.id, error: cancelErr.message }); } } results.refunds.push({ enrollmentId: enrollment.id, studentId: enrollment.studentId, studentEmail: studentData ? studentData.email : null, studentName: studentData ? studentData.fullname : null, totalAmount: enrollment.totalAmount, currency: enrollment.currency || 'USD', refundAmount, completedLessons: completedCount, totalLessons: totalSlots, note: refundNote }); results.processed++; } catch (err) { results.errors.push({ enrollmentId: enrollment.id, error: err.message }); } } // Publish individual Kafka events per student for email notifications try { const { sendMessageToKafka } = require('common'); const db = require('dbLayer'); const coursePack = await db.getCoursePackById(coursePackId); const courseTitle = coursePack ? coursePack.title : 'Unknown Course'; for (const refund of results.refunds) { if (refund.studentEmail) { await sendMessageToKafka('tutorhub-tutorcatalog-service-coursepack-removed-by-admin', { coursePackId, courseTitle, removalReason: removalReason || 'No reason provided', student: { email: refund.studentEmail, fullname: refund.studentName }, refundAmount: refund.refundAmount, totalAmount: refund.totalAmount, currency: refund.currency, completedLessons: refund.completedLessons, totalLessons: refund.totalLessons, refundNote: refund.note, removedAt: new Date().toISOString() }); } } } catch (kafkaErr) { console.log('Warning: failed to publish course removal events:', kafkaErr.message); } return results; } ``` --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## tutorhub-tutorcatalog-service **Version:** `1.0.45` Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. ## 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 TutorCatalog Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our TutorCatalog Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the TutorCatalog Service via HTTP requests for purposes such as creating, updating, deleting and querying TutorCatalog 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 TutorCatalog 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 TutorCatalog 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 | tutorhub-access-token| | Cookie | tutorhub-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 TutorCatalog 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 TutorCatalog service. This service is configured to listen for HTTP requests on port `3000`, 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://tutorhub.prw.mindbricks.com/tutorcatalog-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/tutorcatalog-api` * **Production:** `https://tutorhub.mindbricks.co/tutorcatalog-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 TutorCatalog 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 `TutorCatalog` 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 `TutorCatalog` 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 `TutorCatalog` 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 TutorCatalog 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. ### TutorProfile resource *Resource Definition* : Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. *TutorProfile Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **tutorId** | ID | | | ** | | **certifications** | String | | | *Tutor's certifications (list of certificates, degrees, etc.).* | | **experience** | Text | | | *Brief experience summary or bio.* | | **subjects** | String | | | *Areas of expertise/subjects offered for teaching.* | | **bio** | Text | | | *Optional full-length bio/description.* | | **profilePhoto** | String | | | *Public profile photo URL (may be external or uploaded).* | | **profileStatus** | Enum | | | ** | | **displayName** | String | | | *Tutor's display name, copied from auth user fullname at profile creation.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### profileStatus Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ### CoursePack resource *Resource Definition* : Publicly listed course pack/structured course offered by a tutor. *CoursePack Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **tutorProfileId** | ID | | | ** | | **title** | String | | | ** | | **description** | Text | | | ** | | **price** | Double | | | ** | | **category** | String | | | ** | | **schedulingType** | Enum | | | ** | | **minWeeklyClasses** | Integer | | | ** | | **preliminaryMeetingRequired** | Boolean | | | ** | | **isPublished** | Boolean | | | ** | | **maxDailyLessons** | Integer | | | ** | | **requiredClassesCount** | Integer | | | ** | | **moderationStatus** | Enum | | | *Content moderation status.* | | **moderationNote** | String | | | *Admin note for flagged/removed course packs.* | | **maxPeriodValue** | Integer | | | *Maximum time period value for strict scheduling (e.g. 3 for 3 months)* | | **maxPeriodUnit** | Enum | | | *Time unit for maxPeriodValue in strict scheduling* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### schedulingType Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **flexible** | `"flexible""` | 0 | | **strict** | `"strict""` | 1 | ##### moderationStatus Enum Property *Property Definition* : Content moderation status.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **approved** | `"approved""` | 0 | | **flagged** | `"flagged""` | 1 | | **removed** | `"removed""` | 2 | ##### maxPeriodUnit Enum Property *Property Definition* : Time unit for maxPeriodValue in strict scheduling*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **weeks** | `"weeks""` | 0 | | **months** | `"months""` | 1 | ### CourseMaterial resource *Resource Definition* : Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. *CourseMaterial Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to coursePack.* | | **fileUrl** | String | | | *URL for file/video/document. For downloads or video links (protected).* | | **fileType** | Enum | | | *Type: file, video, document, externalLink.* | | **title** | String | | | *Material title (unique per pack).* | | **description** | Text | | | *Additional details about the material resource.* | | **linkUrl** | String | | | *Optional URL for external resource (if fileType = externalLink).* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### fileType Enum Property *Property Definition* : Type: file, video, document, externalLink.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **file** | `"file""` | 0 | | **video** | `"video""` | 1 | | **document** | `"document""` | 2 | | **externalLink** | `"externalLink""` | 3 | ### CourseCategory resource *Resource Definition* : Represents a course subject/category; used for filtering and navigation. Admin-maintained. *CourseCategory Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **name** | String | | | *Unique category/subject name.* | | **description** | Text | | | *Category description.* | | **icon** | String | | | *Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵)* | ## Business Api ### `Create Tutorprofile` API **Rest Route** The `createTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles` **Rest Request Parameters** The `createTutorProfile` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | bio | Text | false | request.body?.["bio"] | | experience | Text | false | request.body?.["experience"] | | profileStatus | String | false | request.body?.["profileStatus"] | | certifications | String | false | request.body?.["certifications"] | | subjects | String | false | request.body?.["subjects"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | displayName | String | false | request.body?.["displayName"] | **tutorId** : ID of the auth user who is becoming a tutor **bio** : Tutor's biography **experience** : Tutor's experience/qualifications **profileStatus** : Approval status - should be 'approved' when created from auth **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **subjects** : Areas of expertise/subjects offered for teaching. **profilePhoto** : Public profile photo URL (may be external or uploaded). **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/tutorprofiles** ```js axios({ method: 'POST', url: '/v1/tutorprofiles', data: { tutorId:"ID", bio:"Text", experience:"Text", profileStatus:"String", certifications:"String", subjects:"String", profilePhoto:"String", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Tutorprofile` API **[Default update API]** — This is the designated default `update` API for the `tutorProfile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates their own profile. Only owner tutor or admin can update. **Rest Route** The `updateTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` **Rest Request Parameters** The `updateTutorProfile` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | | tutorId | ID | false | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | false | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | **tutorProfileId** : This id paremeter is used to select the required data object that will be updated **tutorId** : **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **experience** : Brief experience summary or bio. **subjects** : Areas of expertise/subjects offered for teaching. **bio** : Optional full-length bio/description. **profilePhoto** : Public profile photo URL (may be external or uploaded). **profileStatus** : **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/tutorprofiles/:tutorProfileId** ```js axios({ method: 'PATCH', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Tutorprofile` API **[Default get API]** — This is the designated default `get` API for the `tutorProfile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly get a tutor profile by ID. No login required. **Rest Route** The `getTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` **Rest Request Parameters** The `getTutorProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | **tutorProfileId** : 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/tutorprofiles/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Tutorprofiles` API **Rest Route** The `listTutorProfiles` API REST controller can be triggered via the following route: `/v1/tutorprofiles` **Rest Request Parameters** The `listTutorProfiles` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/tutorprofiles** ```js axios({ method: 'GET', url: '/v1/tutorprofiles', 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": "tutorProfiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "tutorProfiles": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursepack` API **[Default create API]** — This is the designated default `create` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor creates a new course offering. Only accessible to tutors (or admin, for moderation). **Rest Route** The `createCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks` **Rest Request Parameters** The `createCoursePack` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | true | request.body?.["price"] | | category | String | true | request.body?.["category"] | | schedulingType | Enum | true | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | true | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | true | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | **tutorProfileId** : **title** : **description** : **price** : **category** : **schedulingType** : **minWeeklyClasses** : **preliminaryMeetingRequired** : **isPublished** : **maxDailyLessons** : **requiredClassesCount** : **moderationNote** : Admin note for flagged/removed course packs. **maxPeriodValue** : Maximum time period value for strict scheduling (e.g. 3 for 3 months) **maxPeriodUnit** : Time unit for maxPeriodValue in strict scheduling **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursepacks** ```js axios({ method: 'POST', url: '/v1/coursepacks', data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursepack` API **[Default update API]** — This is the designated default `update` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates their course pack. Only owner tutor or admin can update. Ownership is verified via tutorProfile and user session. **Rest Route** The `updateCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `updateCoursePack` api has got 16 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | false | request.body?.["price"] | | category | String | false | request.body?.["category"] | | schedulingType | Enum | false | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | false | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | false | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationStatus | Enum | false | request.body?.["moderationStatus"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | **coursePackId** : This id paremeter is used to select the required data object that will be updated **tutorProfileId** : **title** : **description** : **price** : **category** : **schedulingType** : **minWeeklyClasses** : **preliminaryMeetingRequired** : **isPublished** : **maxDailyLessons** : **requiredClassesCount** : **moderationStatus** : Content moderation status. **moderationNote** : Admin note for flagged/removed course packs. **maxPeriodValue** : Maximum time period value for strict scheduling (e.g. 3 for 3 months) **maxPeriodUnit** : Time unit for maxPeriodValue in strict scheduling **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursepacks/:coursePackId** ```js axios({ method: 'PATCH', url: `/v1/coursepacks/${coursePackId}`, data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationStatus:"Enum", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursepack` API **[Default delete API]** — This is the designated default `delete` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes their course pack. Only owner tutor or admin can delete. Tutors are blocked if active enrollments exist. Admin can force-delete with a reason, which triggers pro-rata refunds and student notifications. **API Frontend Description By The Backend Architect** Tutors cannot delete a course with active enrollments — they should unpublish instead. Admin can force-delete with a mandatory reason; this triggers automatic pro-rata refunds and email notifications to affected students. **Rest Route** The `deleteCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `deleteCoursePack` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | removalReason | String | | request.body?.["removalReason"] | **coursePackId** : This id paremeter is used to select the required data object that will be deleted **removalReason** : Required when admin deletes a course with active enrollments. Reason is sent to affected students via email. **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/coursepacks/:coursePackId** ```js axios({ method: 'DELETE', url: `/v1/coursepacks/${coursePackId}`, data: { removalReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursepack` API **[Default get API]** — This is the designated default `get` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly get a course pack by ID. No login required. **Rest Route** The `getCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `getCoursePack` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | **coursePackId** : 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/coursepacks/:coursePackId** ```js axios({ method: 'GET', url: `/v1/coursepacks/${coursePackId}`, 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": "coursePack", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coursePack": { "tutorProfile": { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, "isActive": true } } ``` ### `List Coursepacks` API **Rest Route** The `listCoursePacks` API REST controller can be triggered via the following route: `/v1/coursepacks` **Rest Request Parameters** The `listCoursePacks` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursepacks** ```js axios({ method: 'GET', url: '/v1/coursepacks', 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": "coursePacks", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coursePacks": [ { "tutorProfile": [ { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursematerial` API **[Default create API]** — This is the designated default `create` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor uploads a material to a course pack they own. Only tutor or admin can create. **Rest Route** The `createCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials` **Rest Request Parameters** The `createCourseMaterial` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | fileUrl | String | true | request.body?.["fileUrl"] | | fileType | Enum | true | request.body?.["fileType"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | **coursePackId** : FK to coursePack. **fileUrl** : URL for file/video/document. For downloads or video links (protected). **fileType** : Type: file, video, document, externalLink. **title** : Material title (unique per pack). **description** : Additional details about the material resource. **linkUrl** : Optional URL for external resource (if fileType = externalLink). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursematerials** ```js axios({ method: 'POST', url: '/v1/coursematerials', data: { coursePackId:"ID", fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursematerial` API **[Default update API]** — This is the designated default `update` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates course material. Only course's tutor or admin can update. **Rest Route** The `updateCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `updateCourseMaterial` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | | fileUrl | String | false | request.body?.["fileUrl"] | | fileType | Enum | false | request.body?.["fileType"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | **courseMaterialId** : This id paremeter is used to select the required data object that will be updated **fileUrl** : URL for file/video/document. For downloads or video links (protected). **fileType** : Type: file, video, document, externalLink. **title** : Material title (unique per pack). **description** : Additional details about the material resource. **linkUrl** : Optional URL for external resource (if fileType = externalLink). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'PATCH', url: `/v1/coursematerials/${courseMaterialId}`, data: { fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursematerial` API **[Default delete API]** — This is the designated default `delete` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes course material. Only course's tutor or admin can delete. **Rest Route** The `deleteCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `deleteCourseMaterial` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | **courseMaterialId** : 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/coursematerials/:courseMaterialId** ```js axios({ method: 'DELETE', url: `/v1/coursematerials/${courseMaterialId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursematerial` API **[Default get API]** — This is the designated default `get` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get course material. Only accessible by tutor owner or enrolled student or admin. **Rest Route** The `getCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `getCourseMaterial` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | **courseMaterialId** : 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/coursematerials/:courseMaterialId** ```js axios({ method: 'GET', url: `/v1/coursematerials/${courseMaterialId}`, 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": "courseMaterial", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` ### `List Coursematerials` API **[Default list API]** — This is the designated default `list` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List course materials for a coursePack. Only accessible to enrolled students, tutor owner, or admin. **Rest Route** The `listCourseMaterials` API REST controller can be triggered via the following route: `/v1/coursematerials` **Rest Request Parameters** The `listCourseMaterials` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursematerials** ```js axios({ method: 'GET', url: '/v1/coursematerials', 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": "courseMaterials", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseMaterials": [ { "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursecategory` API **[Default create API]** — This is the designated default `create` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin creates new course category/subject tag. **Rest Route** The `createCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories` **Rest Request Parameters** The `createCourseCategory` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | **name** : Unique category/subject name. **description** : Category description. **icon** : Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursecategories** ```js axios({ method: 'POST', url: '/v1/coursecategories', data: { name:"String", description:"Text", icon:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursecategory` API **[Default update API]** — This is the designated default `update` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin updates course category/subject tag. **Rest Route** The `updateCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` **Rest Request Parameters** The `updateCourseCategory` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | | name | String | false | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | **courseCategoryId** : This id paremeter is used to select the required data object that will be updated **name** : Unique category/subject name. **description** : Category description. **icon** : Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursecategories/:courseCategoryId** ```js axios({ method: 'PATCH', url: `/v1/coursecategories/${courseCategoryId}`, data: { name:"String", description:"Text", icon:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursecategory` API **[Default delete API]** — This is the designated default `delete` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin deletes a course category/subject tag. Only admin allowed. **Rest Route** The `deleteCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` **Rest Request Parameters** The `deleteCourseCategory` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | **courseCategoryId** : 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/coursecategories/:courseCategoryId** ```js axios({ method: 'DELETE', url: `/v1/coursecategories/${courseCategoryId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursecategory` API **[Default get API]** — This is the designated default `get` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly fetch a course category/subject by name. No login required. **Rest Route** The `getCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:name` **Rest Request Parameters** The `getCourseCategory` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.params?.["name"] | **name** : Unique category/subject name.. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursecategories/:name** ```js axios({ method: 'GET', url: `/v1/coursecategories/${name}`, 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": "courseCategory", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseCategory": { "isActive": true } } ``` ### `List Coursecategories` API **[Default list API]** — This is the designated default `list` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly list all course categories/subjects for navigation, filtering, and display. No login required. **Rest Route** The `listCourseCategories` API REST controller can be triggered via the following route: `/v1/coursecategories` **Rest Request Parameters** The `listCourseCategories` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursecategories** ```js axios({ method: 'GET', url: '/v1/coursecategories', 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": "courseCategories", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseCategories": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `On Tutorapplicationreviewed` API **API Frontend Description By The Backend Architect** Kafka event handler that creates tutor profile when auth service approves a tutor application. Listens to tutorhub-auth-service-tutorapplication-reviewed topic. **Rest Route** The `onTutorApplicationReviewed` API REST controller can be triggered via the following route: `/v1/ontutorapplicationreviewed` **Rest Request Parameters** The `onTutorApplicationReviewed` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | true | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | **tutorId** : **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **experience** : Brief experience summary or bio. **subjects** : Areas of expertise/subjects offered for teaching. **bio** : Optional full-length bio/description. **profilePhoto** : Public profile photo URL (may be external or uploaded). **profileStatus** : **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/ontutorapplicationreviewed** ```js axios({ method: 'POST', url: '/v1/ontutorapplicationreviewed', data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### 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 ## tutorhub-tutorcatalog-service Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. ## 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 `TutorCatalog` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `TutorCatalog` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `TutorCatalog` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `TutorCatalog` 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 `TutorCatalog` 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 tutorProfile-created **Event topic**: `tutorhub-tutorcatalog-service-dbevent-tutorprofile-created` This event is triggered upon the creation of a `tutorProfile` 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","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent tutorProfile-updated **Event topic**: `tutorhub-tutorcatalog-service-dbevent-tutorprofile-updated` Activation of this event follows the update of a `tutorProfile` data object. The payload contains the updated information under the `tutorProfile` attribute, along with the original data prior to update, labeled as `old_tutorProfile` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_tutorProfile:{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, tutorProfile:{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent tutorProfile-deleted **Event topic**: `tutorhub-tutorcatalog-service-dbevent-tutorprofile-deleted` This event announces the deletion of a `tutorProfile` 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","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent coursePack-created **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursepack-created` This event is triggered upon the creation of a `coursePack` 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","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent coursePack-updated **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursepack-updated` Activation of this event follows the update of a `coursePack` data object. The payload contains the updated information under the `coursePack` attribute, along with the original data prior to update, labeled as `old_coursePack` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_coursePack:{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, coursePack:{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent coursePack-deleted **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursepack-deleted` This event announces the deletion of a `coursePack` 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","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent courseMaterial-created **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursematerial-created` This event is triggered upon the creation of a `courseMaterial` 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","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent courseMaterial-updated **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursematerial-updated` Activation of this event follows the update of a `courseMaterial` data object. The payload contains the updated information under the `courseMaterial` attribute, along with the original data prior to update, labeled as `old_courseMaterial` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_courseMaterial:{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, courseMaterial:{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent courseMaterial-deleted **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursematerial-deleted` This event announces the deletion of a `courseMaterial` 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","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent courseCategory-created **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursecategory-created` This event is triggered upon the creation of a `courseCategory` 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","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent courseCategory-updated **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursecategory-updated` Activation of this event follows the update of a `courseCategory` data object. The payload contains the updated information under the `courseCategory` attribute, along with the original data prior to update, labeled as `old_courseCategory` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_courseCategory:{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, courseCategory:{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent courseCategory-deleted **Event topic**: `tutorhub-tutorcatalog-service-dbevent-coursecategory-deleted` This event announces the deletion of a `courseCategory` 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","name":"String","description":"Text","icon":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` # ElasticSearch Index Events Within the `TutorCatalog` 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 tutorprofile-created **Event topic**: `elastic-index-tutorhub_tutorprofile-created` **Event payload**: ```json {"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event tutorprofile-updated **Event topic**: `elastic-index-tutorhub_tutorprofile-created` **Event payload**: ```json {"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event tutorprofile-deleted **Event topic**: `elastic-index-tutorhub_tutorprofile-deleted` **Event payload**: ```json {"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event tutorprofile-extended **Event topic**: `elastic-index-tutorhub_tutorprofile-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 tutorprofile-created **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-updated **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-retrived **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofiles-listed **Event topic** : `tutorhub-tutorcatalog-service-tutorprofiles-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 `tutorProfiles` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfiles`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","tutorProfiles":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursepack-created **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** 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":"coursePack","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-updated **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"GET","action":"get","appVersion":"Version","rowCount":1,"coursePack":{"tutorProfile":{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},"isActive":true}} ``` ## Route Event coursepacks-listed **Event topic** : `tutorhub-tutorcatalog-service-coursepacks-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 `coursePacks` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePacks`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePacks","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","coursePacks":[{"tutorProfile":[{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursematerial-created **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** 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":"courseMaterial","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-updated **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseMaterial":{"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event coursematerials-listed **Event topic** : `tutorhub-tutorcatalog-service-coursematerials-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 `courseMaterials` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterials`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterials","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseMaterials":[{"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursecategory-created **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** 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":"courseCategory","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-updated **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseCategory":{"isActive":true}} ``` ## Route Event coursecategories-listed **Event topic** : `tutorhub-tutorcatalog-service-coursecategories-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 `courseCategories` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategories`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategories","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseCategories":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event tutorapplicationreviewed-oned **Event topic** : `tutorhub-tutorcatalog-service-tutorapplicationreviewed-oned` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Index Event coursepack-created **Event topic**: `elastic-index-tutorhub_coursepack-created` **Event payload**: ```json {"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursepack-updated **Event topic**: `elastic-index-tutorhub_coursepack-created` **Event payload**: ```json {"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursepack-deleted **Event topic**: `elastic-index-tutorhub_coursepack-deleted` **Event payload**: ```json {"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursepack-extended **Event topic**: `elastic-index-tutorhub_coursepack-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 tutorprofile-created **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-updated **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-retrived **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofiles-listed **Event topic** : `tutorhub-tutorcatalog-service-tutorprofiles-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 `tutorProfiles` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfiles`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","tutorProfiles":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursepack-created **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** 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":"coursePack","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-updated **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"GET","action":"get","appVersion":"Version","rowCount":1,"coursePack":{"tutorProfile":{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},"isActive":true}} ``` ## Route Event coursepacks-listed **Event topic** : `tutorhub-tutorcatalog-service-coursepacks-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 `coursePacks` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePacks`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePacks","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","coursePacks":[{"tutorProfile":[{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursematerial-created **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** 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":"courseMaterial","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-updated **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseMaterial":{"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event coursematerials-listed **Event topic** : `tutorhub-tutorcatalog-service-coursematerials-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 `courseMaterials` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterials`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterials","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseMaterials":[{"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursecategory-created **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** 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":"courseCategory","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-updated **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseCategory":{"isActive":true}} ``` ## Route Event coursecategories-listed **Event topic** : `tutorhub-tutorcatalog-service-coursecategories-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 `courseCategories` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategories`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategories","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseCategories":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event tutorapplicationreviewed-oned **Event topic** : `tutorhub-tutorcatalog-service-tutorapplicationreviewed-oned` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Index Event coursematerial-created **Event topic**: `elastic-index-tutorhub_coursematerial-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursematerial-updated **Event topic**: `elastic-index-tutorhub_coursematerial-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursematerial-deleted **Event topic**: `elastic-index-tutorhub_coursematerial-deleted` **Event payload**: ```json {"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursematerial-extended **Event topic**: `elastic-index-tutorhub_coursematerial-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 tutorprofile-created **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-updated **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-retrived **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofiles-listed **Event topic** : `tutorhub-tutorcatalog-service-tutorprofiles-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 `tutorProfiles` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfiles`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","tutorProfiles":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursepack-created **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** 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":"coursePack","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-updated **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"GET","action":"get","appVersion":"Version","rowCount":1,"coursePack":{"tutorProfile":{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},"isActive":true}} ``` ## Route Event coursepacks-listed **Event topic** : `tutorhub-tutorcatalog-service-coursepacks-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 `coursePacks` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePacks`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePacks","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","coursePacks":[{"tutorProfile":[{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursematerial-created **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** 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":"courseMaterial","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-updated **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseMaterial":{"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event coursematerials-listed **Event topic** : `tutorhub-tutorcatalog-service-coursematerials-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 `courseMaterials` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterials`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterials","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseMaterials":[{"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursecategory-created **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** 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":"courseCategory","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-updated **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseCategory":{"isActive":true}} ``` ## Route Event coursecategories-listed **Event topic** : `tutorhub-tutorcatalog-service-coursecategories-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 `courseCategories` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategories`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategories","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseCategories":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event tutorapplicationreviewed-oned **Event topic** : `tutorhub-tutorcatalog-service-tutorapplicationreviewed-oned` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Index Event coursecategory-created **Event topic**: `elastic-index-tutorhub_coursecategory-created` **Event payload**: ```json {"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursecategory-updated **Event topic**: `elastic-index-tutorhub_coursecategory-created` **Event payload**: ```json {"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursecategory-deleted **Event topic**: `elastic-index-tutorhub_coursecategory-deleted` **Event payload**: ```json {"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event coursecategory-extended **Event topic**: `elastic-index-tutorhub_coursecategory-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 tutorprofile-created **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-updated **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofile-retrived **Event topic** : `tutorhub-tutorcatalog-service-tutorprofile-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 `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorprofiles-listed **Event topic** : `tutorhub-tutorcatalog-service-tutorprofiles-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 `tutorProfiles` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfiles`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"tutorProfiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","tutorProfiles":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursepack-created **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** 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":"coursePack","method":"POST","action":"create","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-updated **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"coursePack":{"id":"ID","tutorProfileId":"ID","title":"String","description":"Text","price":"Double","category":"String","schedulingType":"Enum","schedulingType_idx":"Integer","minWeeklyClasses":"Integer","preliminaryMeetingRequired":"Boolean","isPublished":"Boolean","maxDailyLessons":"Integer","requiredClassesCount":"Integer","moderationStatus":"Enum","moderationStatus_idx":"Integer","moderationNote":"String","maxPeriodValue":"Integer","maxPeriodUnit":"Enum","maxPeriodUnit_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursepack-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursepack-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 `coursePack` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePack`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePack","method":"GET","action":"get","appVersion":"Version","rowCount":1,"coursePack":{"tutorProfile":{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},"isActive":true}} ``` ## Route Event coursepacks-listed **Event topic** : `tutorhub-tutorcatalog-service-coursepacks-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 `coursePacks` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`coursePacks`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"coursePacks","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","coursePacks":[{"tutorProfile":[{"tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","displayName":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursematerial-created **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** 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":"courseMaterial","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-updated **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseMaterial":{"id":"ID","coursePackId":"ID","fileUrl":"String","fileType":"Enum","fileType_idx":"Integer","title":"String","description":"Text","linkUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursematerial-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursematerial-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 `courseMaterial` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterial`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterial","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseMaterial":{"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event coursematerials-listed **Event topic** : `tutorhub-tutorcatalog-service-coursematerials-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 `courseMaterials` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseMaterials`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseMaterials","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseMaterials":[{"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event coursecategory-created **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** 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":"courseCategory","method":"POST","action":"create","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-updated **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-deleted **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"courseCategory":{"id":"ID","name":"String","description":"Text","icon":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event coursecategory-retrived **Event topic** : `tutorhub-tutorcatalog-service-coursecategory-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 `courseCategory` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategory`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategory","method":"GET","action":"get","appVersion":"Version","rowCount":1,"courseCategory":{"isActive":true}} ``` ## Route Event coursecategories-listed **Event topic** : `tutorhub-tutorcatalog-service-coursecategories-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 `courseCategories` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`courseCategories`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"courseCategories","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","courseCategories":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event tutorapplicationreviewed-oned **Event topic** : `tutorhub-tutorcatalog-service-tutorapplicationreviewed-oned` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `tutorProfile` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`tutorProfile`** 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":"tutorProfile","method":"POST","action":"create","appVersion":"Version","rowCount":1,"tutorProfile":{"id":"ID","tutorId":"ID","certifications":"String","experience":"Text","subjects":"String","bio":"Text","profilePhoto":"String","profileStatus":"Enum","profileStatus_idx":"Integer","displayName":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` # 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 tutorProfile # Service Design Specification - Object Design for tutorProfile **tutorhub-tutorcatalog-service** documentation ## Document Overview This document outlines the object design for the `tutorProfile` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## tutorProfile Data Object ### Object Overview **Description:** Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. 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:** accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `tutorId` | ID | Yes | - | | `certifications` | String | No | Tutor's certifications (list of certificates, degrees, etc.). | | `experience` | Text | No | Brief experience summary or bio. | | `subjects` | String | No | Areas of expertise/subjects offered for teaching. | | `bio` | Text | No | Optional full-length bio/description. | | `profilePhoto` | String | No | Public profile photo URL (may be external or uploaded). | | `profileStatus` | Enum | Yes | - | | `displayName` | String | No | Tutor's display name, copied from auth user fullname at profile creation. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `certifications` `subjects` 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. - **tutorId**: '00000000-0000-0000-0000-000000000000' - **profileStatus**: pending ### Auto Update Properties `tutorId` `certifications` `experience` `subjects` `bio` `profilePhoto` `profileStatus` `displayName` 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. - **profileStatus**: [pending, approved, rejected] ### Elastic Search Indexing `tutorId` `certifications` `experience` `subjects` `bio` `profilePhoto` `profileStatus` `displayName` 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 `tutorId` `profileStatus` 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 `tutorId` 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 `tutorId` 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 `tutorId` 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. - **tutorId**: 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 `tutorId` `profileStatus` 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. - **tutorId**: ID has a filter named `tutorId` - **profileStatus**: Enum has a filter named `profileStatus` --- ### Service Design Specification - Object Design for coursePack # Service Design Specification - Object Design for coursePack **tutorhub-tutorcatalog-service** documentation ## Document Overview This document outlines the object design for the `coursePack` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## coursePack Data Object ### Object Overview **Description:** Publicly listed course pack/structured course offered by a tutor. 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 - **coursePackByTutorAndTitle**: [tutorProfileId, title] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema **Display Label Property:** `title` — 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 | |----------|------|----------|-------------| | `tutorProfileId` | ID | Yes | - | | `title` | String | Yes | - | | `description` | Text | No | - | | `price` | Double | Yes | - | | `category` | String | Yes | - | | `schedulingType` | Enum | Yes | - | | `minWeeklyClasses` | Integer | No | - | | `preliminaryMeetingRequired` | Boolean | Yes | - | | `isPublished` | Boolean | Yes | - | | `maxDailyLessons` | Integer | No | - | | `requiredClassesCount` | Integer | No | - | | `moderationStatus` | Enum | No | Content moderation status. | | `moderationNote` | String | No | Admin note for flagged/removed course packs. | | `maxPeriodValue` | Integer | No | Maximum time period value for strict scheduling (e.g. 3 for 3 months) | | `maxPeriodUnit` | Enum | No | Time unit for maxPeriodValue in strict scheduling | * 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. - **tutorProfileId**: '00000000-0000-0000-0000-000000000000' - **title**: 'default' - **price**: 0.0 - **category**: 'default' - **schedulingType**: flexible - **isPublished**: true - **moderationStatus**: approved ### 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. - **moderationStatus**: Will be created with value `approved` ### Auto Update Properties `tutorProfileId` `title` `description` `price` `category` `schedulingType` `minWeeklyClasses` `preliminaryMeetingRequired` `isPublished` `maxDailyLessons` `requiredClassesCount` `moderationStatus` `moderationNote` `maxPeriodValue` `maxPeriodUnit` 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. - **schedulingType**: [flexible, strict] - **moderationStatus**: [approved, flagged, removed] - **maxPeriodUnit**: [weeks, months] ### Elastic Search Indexing `tutorProfileId` `title` `description` `price` `category` `schedulingType` `minWeeklyClasses` `preliminaryMeetingRequired` `isPublished` `maxDailyLessons` `requiredClassesCount` `moderationStatus` `maxPeriodValue` `maxPeriodUnit` 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 `tutorProfileId` `title` `category` `isPublished` `moderationStatus` 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 `tutorProfileId` 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 `tutorProfileId` `category` 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. - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **category**: String Relation to `courseCategory`.name 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: No ### Filter Properties `tutorProfileId` `title` `category` `schedulingType` `isPublished` `moderationStatus` 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. - **tutorProfileId**: ID has a filter named `tutorProfileId` - **title**: String has a filter named `courseTitle` - **category**: String has a filter named `category` - **schedulingType**: Enum has a filter named `scheduling` - **isPublished**: Boolean has a filter named `published` - **moderationStatus**: Enum has a filter named `moderationStatus` --- ### Service Design Specification - Object Design for courseMaterial # Service Design Specification - Object Design for courseMaterial **tutorhub-tutorcatalog-service** documentation ## Document Overview This document outlines the object design for the `courseMaterial` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## courseMaterial Data Object ### Object Overview **Description:** Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. 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 - **materialPerCourseTitle**: [coursePackId, title] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema **Display Label Property:** `title` — 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 | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to coursePack. | | `fileUrl` | String | Yes | URL for file/video/document. For downloads or video links (protected). | | `fileType` | Enum | Yes | Type: file, video, document, externalLink. | | `title` | String | Yes | Material title (unique per pack). | | `description` | Text | No | Additional details about the material resource. | | `linkUrl` | String | No | Optional URL for external resource (if fileType = externalLink). | * 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. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **fileUrl**: 'default' - **fileType**: "file" - **title**: 'default' ### Constant Properties `coursePackId` 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 `fileUrl` `fileType` `title` `description` `linkUrl` 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. - **fileType**: [file, video, document, externalLink] ### Elastic Search Indexing `coursePackId` `fileType` `title` `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 `coursePackId` `title` 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 `coursePackId` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Relation Properties `coursePackId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Filter Properties `fileType` 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. - **fileType**: Enum has a filter named `type` --- ### Service Design Specification - Object Design for courseCategory # Service Design Specification - Object Design for courseCategory **tutorhub-tutorcatalog-service** documentation ## Document Overview This document outlines the object design for the `courseCategory` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## courseCategory Data Object ### Object Overview **Description:** Represents a course subject/category; used for filtering and navigation. Admin-maintained. 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:** accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **uniqueCategoryName**: [name] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema **Display Label Property:** `name` — 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 | |----------|------|----------|-------------| | `name` | String | Yes | Unique category/subject name. | | `description` | Text | No | Category description. | | `icon` | String | No | Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) | * 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. - **name**: 'default' - **icon**: 📚 ### Auto Update Properties `name` `description` `icon` 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 `name` `description` `icon` 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 `name` `icon` 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 `name` 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 `name` 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 `name` 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. - **name**: String has a filter named `name` --- ## Business APIs ### Business API Design Specification - `Create Tutorprofile` # Business API Design Specification - `Create Tutorprofile` 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 `createTutorProfile` 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 `createTutorProfile` Business API is designed to handle a `create` operation on the `TutorProfile` 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 `tutorprofile-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 `createTutorProfile` Business API includes a REST controller that can be triggered via the following route: `/v1/tutorprofiles` 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 `createTutorProfile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createTutorProfile` Business API has 9 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `No` | `-` | `body` | `tutorProfileId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `tutorId` | `ID` | `Yes` | `-` | `body` | `tutorId` | | **Description:** | ID of the auth user who is becoming a tutor | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Tutor's biography | | | | | | | | | | | | | `experience` | `Text` | `No` | `-` | `body` | `experience` | | **Description:** | Tutor's experience/qualifications | | | | | | | | | | | | | `profileStatus` | `String` | `No` | `pending` | `body` | `profileStatus` | | **Description:** | Approval status - should be 'approved' when created from auth | | | | | | | | | | | | | `certifications` | `String` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor's certifications (list of certificates, degrees, etc.). | | | | | | | | | | | | | `subjects` | `String` | `No` | `-` | `body` | `subjects` | | **Description:** | Areas of expertise/subjects offered for teaching. | | | | | | | | | | | | | `profilePhoto` | `String` | `No` | `-` | `body` | `profilePhoto` | | **Description:** | Public profile photo URL (may be external or uploaded). | | | | | | | | | | | | | `displayName` | `String` | `No` | `-` | `body` | `displayName` | | **Description:** | Tutor's display name, copied from auth user fullname at profile creation. | | | | | | | | | | | | ### 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 `createTutorProfile` 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** *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.tutorProfileId, tutorId: this.tutorId, certifications: this.certifications, experience: this.experience, subjects: this.subjects, bio: this.bio, profilePhoto: this.profilePhoto, profileStatus: this.profileStatus, displayName: this.displayName, 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 `createTutorProfile` api has got 8 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | bio | Text | false | request.body?.["bio"] | | experience | Text | false | request.body?.["experience"] | | profileStatus | String | false | request.body?.["profileStatus"] | | certifications | String | false | request.body?.["certifications"] | | subjects | String | false | request.body?.["subjects"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | displayName | String | false | request.body?.["displayName"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/tutorprofiles** ```js axios({ method: 'POST', url: '/v1/tutorprofiles', data: { tutorId:"ID", bio:"Text", experience:"Text", profileStatus:"String", certifications:"String", subjects:"String", profilePhoto:"String", displayName:"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 **`tutorProfile`** 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": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Tutorprofile` # Business API Design Specification - `Update Tutorprofile` 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 `updateTutorProfile` 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 `updateTutorProfile` Business API is designed to handle a `update` operation on the `TutorProfile` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor updates their own profile. Only owner tutor or admin can update. ## 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 `tutorprofile-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 `updateTutorProfile` Business API includes a REST controller that can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` 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 `updateTutorProfile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateTutorProfile` Business API has 9 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `Yes` | `-` | `urlpath` | `tutorProfileId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `tutorId` | `ID` | `No` | `-` | `body` | `tutorId` | | **Description:** | - | | | | | | | | | | | | | `certifications` | `String` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor's certifications (list of certificates, degrees, etc.). | | | | | | | | | | | | | `experience` | `Text` | `No` | `-` | `body` | `experience` | | **Description:** | Brief experience summary or bio. | | | | | | | | | | | | | `subjects` | `String` | `No` | `-` | `body` | `subjects` | | **Description:** | Areas of expertise/subjects offered for teaching. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Optional full-length bio/description. | | | | | | | | | | | | | `profilePhoto` | `String` | `No` | `-` | `body` | `profilePhoto` | | **Description:** | Public profile photo URL (may be external or uploaded). | | | | | | | | | | | | | `profileStatus` | `Enum` | `No` | `-` | `body` | `profileStatus` | | **Description:** | - | | | | | | | | | | | | | `displayName` | `String` | `No` | `-` | `body` | `displayName` | | **Description:** | Tutor's display name, copied from auth user fullname at profile creation. | | | | | | | | | | | | ### 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 `updateTutorProfile` 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: `[tutor, 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.tutorProfileId},{isActive:true}]}), {"path":"services[1].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 { tutorId: this.tutorId, certifications: this.certifications ? this.certifications : ( this.certifications_remove ? sequelize.fn('array_remove', sequelize.col('certifications'), this.certifications_remove) : (this.certifications_append ? sequelize.fn('array_append', sequelize.col('certifications'), this.certifications_append) : undefined)) , experience: this.experience, subjects: this.subjects ? this.subjects : ( this.subjects_remove ? sequelize.fn('array_remove', sequelize.col('subjects'), this.subjects_remove) : (this.subjects_append ? sequelize.fn('array_append', sequelize.col('subjects'), this.subjects_append) : undefined)) , bio: this.bio, profilePhoto: this.profilePhoto, profileStatus: this.profileStatus, displayName: this.displayName, } ``` ## 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 `updateTutorProfile` api has got 9 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | | tutorId | ID | false | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | false | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/tutorprofiles/:tutorProfileId** ```js axios({ method: 'PATCH', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"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 **`tutorProfile`** 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": "tutorProfile", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Tutorprofile` # Business API Design Specification - `Get Tutorprofile` 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 `getTutorProfile` 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 `getTutorProfile` Business API is designed to handle a `get` operation on the `TutorProfile` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Publicly get a tutor profile by ID. No login required. ## 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 `tutorprofile-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** : `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 `getTutorProfile` Business API includes a REST controller that can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` 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 `getTutorProfile` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getTutorProfile` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `Yes` | `-` | `urlpath` | `tutorProfileId` | | **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 `getTutorProfile` 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: `[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.tutorProfileId},{isActive:true}]}), {"path":"services[1].businessLogic[2].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 `getTutorProfile` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/tutorprofiles/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/tutorprofiles/${tutorProfileId}`, 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 **`tutorProfile`** 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": "tutorProfile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Tutorprofiles` # Business API Design Specification - `List Tutorprofiles` 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 `listTutorProfiles` 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 `listTutorProfiles` Business API is designed to handle a `list` operation on the `TutorProfile` 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 `tutorprofiles-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 `listTutorProfiles` Business API includes a REST controller that can be triggered via the following route: `/v1/tutorprofiles` 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 `listTutorProfiles` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listTutorProfiles` 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 `listTutorProfiles` 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`,`tutorId`,`certifications`,`experience`,`subjects`,`bio`,`profilePhoto`,`profileStatus`,`displayName` ## 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. ```js // Addtional Clause Name : filterByTutorId // condition doWhen // this.queryData?.tutorId != null // condition excludeWhen // No excludeWhen condtion defined // clause object { tutorId: this.queryData.tutorId } ``` **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[3].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 `listTutorProfiles` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/tutorprofiles** ```js axios({ method: 'GET', url: '/v1/tutorprofiles', 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 **`tutorProfiles`** 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": "tutorProfiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "tutorProfiles": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Coursepack` # Business API Design Specification - `Create Coursepack` 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 `createCoursePack` 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 `createCoursePack` Business API is designed to handle a `create` operation on the `CoursePack` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor creates a new course offering. Only accessible to tutors (or admin, for moderation). ## 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 `coursepack-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 `createCoursePack` Business API includes a REST controller that can be triggered via the following route: `/v1/coursepacks` 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 `createCoursePack` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createCoursePack` Business API has 15 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coursePackId` | `ID` | `No` | `-` | `body` | `coursePackId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `tutorProfileId` | `ID` | `Yes` | `-` | `body` | `tutorProfileId` | | **Description:** | - | | | | | | | | | | | | | `title` | `String` | `Yes` | `-` | `body` | `title` | | **Description:** | - | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | - | | | | | | | | | | | | | `price` | `Double` | `Yes` | `-` | `body` | `price` | | **Description:** | - | | | | | | | | | | | | | `category` | `String` | `Yes` | `-` | `body` | `category` | | **Description:** | - | | | | | | | | | | | | | `schedulingType` | `Enum` | `Yes` | `-` | `body` | `schedulingType` | | **Description:** | - | | | | | | | | | | | | | `minWeeklyClasses` | `Integer` | `No` | `-` | `body` | `minWeeklyClasses` | | **Description:** | - | | | | | | | | | | | | | `preliminaryMeetingRequired` | `Boolean` | `Yes` | `-` | `body` | `preliminaryMeetingRequired` | | **Description:** | - | | | | | | | | | | | | | `isPublished` | `Boolean` | `Yes` | `-` | `body` | `isPublished` | | **Description:** | - | | | | | | | | | | | | | `maxDailyLessons` | `Integer` | `No` | `-` | `body` | `maxDailyLessons` | | **Description:** | - | | | | | | | | | | | | | `requiredClassesCount` | `Integer` | `No` | `-` | `body` | `requiredClassesCount` | | **Description:** | - | | | | | | | | | | | | | `moderationNote` | `String` | `No` | `-` | `body` | `moderationNote` | | **Description:** | Admin note for flagged/removed course packs. | | | | | | | | | | | | | `maxPeriodValue` | `Integer` | `No` | `-` | `body` | `maxPeriodValue` | | **Description:** | Maximum time period value for strict scheduling (e.g. 3 for 3 months) | | | | | | | | | | | | | `maxPeriodUnit` | `Enum` | `No` | `-` | `body` | `maxPeriodUnit` | | **Description:** | Time unit for maxPeriodValue in strict scheduling | | | | | | | | | | | | ### 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 `createCoursePack` 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: `[tutor, 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.coursePackId, tutorProfileId: this.tutorProfileId, title: this.title, description: this.description, price: this.price, category: this.category, schedulingType: this.schedulingType, minWeeklyClasses: this.minWeeklyClasses, preliminaryMeetingRequired: this.preliminaryMeetingRequired, isPublished: this.isPublished, maxDailyLessons: this.maxDailyLessons, requiredClassesCount: this.requiredClassesCount, moderationNote: this.moderationNote, maxPeriodValue: this.maxPeriodValue, maxPeriodUnit: this.maxPeriodUnit, 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 `createCoursePack` api has got 14 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | true | request.body?.["price"] | | category | String | true | request.body?.["category"] | | schedulingType | Enum | true | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | true | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | true | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/coursepacks** ```js axios({ method: 'POST', url: '/v1/coursepacks', data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"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 **`coursePack`** 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": "coursePack", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Coursepack` # Business API Design Specification - `Update Coursepack` 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 `updateCoursePack` 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 `updateCoursePack` Business API is designed to handle a `update` operation on the `CoursePack` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor updates their course pack. Only owner tutor or admin can update. Ownership is verified via tutorProfile and user session. ## 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 `coursepack-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 `updateCoursePack` Business API includes a REST controller that can be triggered via the following route: `/v1/coursepacks/:coursePackId` 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 `updateCoursePack` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateCoursePack` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `urlpath` | `coursePackId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `tutorProfileId` | `ID` | `No` | `-` | `body` | `tutorProfileId` | | **Description:** | - | | | | | | | | | | | | | `title` | `String` | `No` | `-` | `body` | `title` | | **Description:** | - | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | - | | | | | | | | | | | | | `price` | `Double` | `No` | `-` | `body` | `price` | | **Description:** | - | | | | | | | | | | | | | `category` | `String` | `No` | `-` | `body` | `category` | | **Description:** | - | | | | | | | | | | | | | `schedulingType` | `Enum` | `No` | `-` | `body` | `schedulingType` | | **Description:** | - | | | | | | | | | | | | | `minWeeklyClasses` | `Integer` | `No` | `-` | `body` | `minWeeklyClasses` | | **Description:** | - | | | | | | | | | | | | | `preliminaryMeetingRequired` | `Boolean` | `No` | `-` | `body` | `preliminaryMeetingRequired` | | **Description:** | - | | | | | | | | | | | | | `isPublished` | `Boolean` | `No` | `-` | `body` | `isPublished` | | **Description:** | - | | | | | | | | | | | | | `maxDailyLessons` | `Integer` | `No` | `-` | `body` | `maxDailyLessons` | | **Description:** | - | | | | | | | | | | | | | `requiredClassesCount` | `Integer` | `No` | `-` | `body` | `requiredClassesCount` | | **Description:** | - | | | | | | | | | | | | | `moderationStatus` | `Enum` | `No` | `-` | `body` | `moderationStatus` | | **Description:** | Content moderation status. | | | | | | | | | | | | | `moderationNote` | `String` | `No` | `-` | `body` | `moderationNote` | | **Description:** | Admin note for flagged/removed course packs. | | | | | | | | | | | | | `maxPeriodValue` | `Integer` | `No` | `-` | `body` | `maxPeriodValue` | | **Description:** | Maximum time period value for strict scheduling (e.g. 3 for 3 months) | | | | | | | | | | | | | `maxPeriodUnit` | `Enum` | `No` | `-` | `body` | `maxPeriodUnit` | | **Description:** | Time unit for maxPeriodValue in strict scheduling | | | | | | | | | | | | ### 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 `updateCoursePack` 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: `[tutor, 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.coursePackId},{isActive:true}]}), {"path":"services[1].businessLogic[5].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 { tutorProfileId: this.tutorProfileId, title: this.title, description: this.description, price: this.price, category: this.category, schedulingType: this.schedulingType, minWeeklyClasses: this.minWeeklyClasses, preliminaryMeetingRequired: this.preliminaryMeetingRequired, isPublished: this.isPublished, maxDailyLessons: this.maxDailyLessons, requiredClassesCount: this.requiredClassesCount, moderationStatus: this.moderationStatus, moderationNote: this.moderationNote, maxPeriodValue: this.maxPeriodValue, maxPeriodUnit: this.maxPeriodUnit, } ``` ## 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 `updateCoursePack` api has got 16 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | false | request.body?.["price"] | | category | String | false | request.body?.["category"] | | schedulingType | Enum | false | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | false | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | false | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationStatus | Enum | false | request.body?.["moderationStatus"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/coursepacks/:coursePackId** ```js axios({ method: 'PATCH', url: `/v1/coursepacks/${coursePackId}`, data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationStatus:"Enum", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"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 **`coursePack`** 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": "coursePack", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Coursepack` # Business API Design Specification - `Delete Coursepack` 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 `deleteCoursePack` 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 `deleteCoursePack` Business API is designed to handle a `delete` operation on the `CoursePack` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor deletes their course pack. Only owner tutor or admin can delete. Tutors are blocked if active enrollments exist. Admin can force-delete with a reason, which triggers pro-rata refunds and student notifications. ## API Frontend Description By The Backend Architect Tutors cannot delete a course with active enrollments — they should unpublish instead. Admin can force-delete with a mandatory reason; this triggers automatic pro-rata refunds and email notifications to affected students. ## 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 `coursepack-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 `deleteCoursePack` Business API includes a REST controller that can be triggered via the following route: `/v1/coursepacks/:coursePackId` 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 `deleteCoursePack` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteCoursePack` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `urlpath` | `coursePackId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | | `removalReason` | `String` | `No` | `-` | `body` | `removalReason` | | **Description:** | Required when admin deletes a course with active enrollments. Reason is sent to affected students via email. | | | | | | | | | | | | ### 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 `deleteCoursePack` 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: `[tutor, 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.coursePackId},{isActive:true}]}), {"path":"services[1].businessLogic[6].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] Action : checkActiveEnrollments **Action Type**: `FunctionCallAction` Check if this course pack has any active enrollments before allowing deletion ```js class Api { async checkActiveEnrollments() { try { return await runMScript( () => (async () => await LIB.checkCoursePackActiveEnrollments(this.coursePackId))(), { path: "services[1].businessLogic[6].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction checkActiveEnrollments:", err); throw err; } } } ``` --- ### [9] Action : blockTutorDeleteWithEnrollments **Action Type**: `ValidationAction` Block tutors from deleting courses that have active enrollments. They should unpublish instead. ```js class Api { async blockTutorDeleteWithEnrollments() { const isValid = runMScript( () => !( this.session.roleId === "tutor" && this.enrollmentCheck && this.enrollmentCheck.hasActiveEnrollments ), { path: "services[1].businessLogic[6].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError( "You cannot delete a course with active enrollments. Please unpublish the course instead so existing students can continue their lessons.", ); } return isValid; } } ``` --- ### [10] Action : requireReasonForAdminCascade **Action Type**: `ValidationAction` Admin must provide a removal reason when deleting a course with active enrollments ```js class Api { async requireReasonForAdminCascade() { const isValid = runMScript( () => !( this.session.roleId === "admin" && this.enrollmentCheck && this.enrollmentCheck.hasActiveEnrollments && (!this.removalReason || this.removalReason.trim().length === 0) ), { path: "services[1].businessLogic[6].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new BadRequestError( "A removal reason is required when deleting a course with active enrollments. This reason will be sent to affected students.", ); } return isValid; } } ``` --- ### [11] Action : triggerCascadeRefunds **Action Type**: `FunctionCallAction` Admin cascade: trigger pro-rata refunds for all active enrollments and notify students ```js class Api { async triggerCascadeRefunds() { try { return await runMScript( () => (async () => await LIB.triggerAdminCourseRemovalCascade( this.coursePackId, this.removalReason, this.enrollmentCheck, this.session, ))(), { path: "services[1].businessLogic[6].actions.functionCallActions[1].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction triggerCascadeRefunds:", err); throw err; } } } ``` --- ### [12] Step : checkInstance Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement. --- ### [13] 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` --- ### [14] Action : addCascadeInfo **Action Type**: `AddToResponseAction` ```js class Api { async addCascadeInfo() { try { this.output["cascadeResult"] = runMScript(() => this.cascadeResult, { path: "services[1].businessLogic[6].actions.addToResponseActions[0].context[0].contextValue", }); return true; } catch (error) { console.error("AddToResponseAction error:", error); throw error; } } } ``` --- ### [15] Step : buildOutput Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output. --- ### [16] Step : sendResponse Manager delivers the response to the client and finalizes any temporary internal structures. --- ### [17] 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 `deleteCoursePack` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | removalReason | String | | request.body?.["removalReason"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/coursepacks/:coursePackId** ```js axios({ method: 'DELETE', url: `/v1/coursepacks/${coursePackId}`, data: { removalReason:"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 **`coursePack`** 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": "coursePack", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Coursepack` # Business API Design Specification - `Get Coursepack` 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 `getCoursePack` 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 `getCoursePack` Business API is designed to handle a `get` operation on the `CoursePack` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Publicly get a course pack by ID. No login required. ## 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 `coursepack-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** : `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 `getCoursePack` Business API includes a REST controller that can be triggered via the following route: `/v1/coursepacks/:coursePackId` 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 `getCoursePack` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getCoursePack` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `urlpath` | `coursePackId` | | **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 `getCoursePack` 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: `[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.", `id`,`tutorProfileId`,`title`,`description`,`price`,`category`,`schedulingType`,`minWeeklyClasses`,`requiredClassesCount`,`maxPeriodValue`,`maxPeriodUnit`,`preliminaryMeetingRequired`,`isPublished` ## 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.coursePackId},{isActive:true}]}), {"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 `getCoursePack` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coursepacks/:coursePackId** ```js axios({ method: 'GET', url: `/v1/coursepacks/${coursePackId}`, 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 **`coursePack`** 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": "coursePack", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coursePack": { "tutorProfile": { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, "isActive": true } } ``` --- ### Business API Design Specification - `List Coursepacks` # Business API Design Specification - `List Coursepacks` 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 `listCoursePacks` 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 `listCoursePacks` Business API is designed to handle a `list` operation on the `CoursePack` 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 `coursepacks-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 `listCoursePacks` Business API includes a REST controller that can be triggered via the following route: `/v1/coursepacks` 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 `listCoursePacks` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listCoursePacks` 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 `listCoursePacks` 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`,`tutorProfileId`,`title`,`description`,`price`,`category`,`schedulingType`,`minWeeklyClasses`,`requiredClassesCount`,`maxPeriodValue`,`maxPeriodUnit`,`preliminaryMeetingRequired`,`isPublished`,`moderationStatus`,`moderationNote` ## 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. ```js // Addtional Clause Name : filterByTutorProfile // condition doWhen // this.queryData?.tutorProfileId != null // condition excludeWhen // No excludeWhen condtion defined // clause object { tutorProfileId: this.queryData.tutorProfileId } ``` **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[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). [ title asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. List is grouped by the followinf field(s) : [ category ] **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 `listCoursePacks` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coursepacks** ```js axios({ method: 'GET', url: '/v1/coursepacks', 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 **`coursePacks`** 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": "coursePacks", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coursePacks": [ { "tutorProfile": [ { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Coursematerial` # Business API Design Specification - `Create Coursematerial` 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 `createCourseMaterial` 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 `createCourseMaterial` Business API is designed to handle a `create` operation on the `CourseMaterial` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor uploads a material to a course pack they own. Only tutor or admin can create. ## 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 `coursematerial-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 `createCourseMaterial` Business API includes a REST controller that can be triggered via the following route: `/v1/coursematerials` 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 `createCourseMaterial` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createCourseMaterial` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseMaterialId` | `ID` | `No` | `-` | `body` | `courseMaterialId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `body` | `coursePackId` | | **Description:** | FK to coursePack. | | | | | | | | | | | | | `fileUrl` | `String` | `Yes` | `-` | `body` | `fileUrl` | | **Description:** | URL for file/video/document. For downloads or video links (protected). | | | | | | | | | | | | | `fileType` | `Enum` | `Yes` | `-` | `body` | `fileType` | | **Description:** | Type: file, video, document, externalLink. | | | | | | | | | | | | | `title` | `String` | `Yes` | `-` | `body` | `title` | | **Description:** | Material title (unique per pack). | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Additional details about the material resource. | | | | | | | | | | | | | `linkUrl` | `String` | `No` | `-` | `body` | `linkUrl` | | **Description:** | Optional URL for external resource (if fileType = externalLink). | | | | | | | | | | | | ### 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 `createCourseMaterial` 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: `[tutor, 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.courseMaterialId, coursePackId: this.coursePackId, fileUrl: this.fileUrl, fileType: this.fileType, title: this.title, description: this.description, linkUrl: this.linkUrl, 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 `createCourseMaterial` api has got 6 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | fileUrl | String | true | request.body?.["fileUrl"] | | fileType | Enum | true | request.body?.["fileType"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/coursematerials** ```js axios({ method: 'POST', url: '/v1/coursematerials', data: { coursePackId:"ID", fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"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 **`courseMaterial`** 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": "courseMaterial", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Coursematerial` # Business API Design Specification - `Update Coursematerial` 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 `updateCourseMaterial` 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 `updateCourseMaterial` Business API is designed to handle a `update` operation on the `CourseMaterial` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor updates course material. Only course's tutor or admin can update. ## 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 `coursematerial-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 `updateCourseMaterial` Business API includes a REST controller that can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` 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 `updateCourseMaterial` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateCourseMaterial` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseMaterialId` | `ID` | `Yes` | `-` | `urlpath` | `courseMaterialId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `fileUrl` | `String` | `No` | `-` | `body` | `fileUrl` | | **Description:** | URL for file/video/document. For downloads or video links (protected). | | | | | | | | | | | | | `fileType` | `Enum` | `No` | `-` | `body` | `fileType` | | **Description:** | Type: file, video, document, externalLink. | | | | | | | | | | | | | `title` | `String` | `No` | `-` | `body` | `title` | | **Description:** | Material title (unique per pack). | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Additional details about the material resource. | | | | | | | | | | | | | `linkUrl` | `String` | `No` | `-` | `body` | `linkUrl` | | **Description:** | Optional URL for external resource (if fileType = externalLink). | | | | | | | | | | | | ### 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 `updateCourseMaterial` 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: `[tutor, 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.courseMaterialId},{isActive:true}]}), {"path":"services[1].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** *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 { fileUrl: this.fileUrl, fileType: this.fileType, title: this.title, description: this.description, linkUrl: this.linkUrl, } ``` ## 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 `updateCourseMaterial` api has got 6 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | | fileUrl | String | false | request.body?.["fileUrl"] | | fileType | Enum | false | request.body?.["fileType"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'PATCH', url: `/v1/coursematerials/${courseMaterialId}`, data: { fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"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 **`courseMaterial`** 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": "courseMaterial", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Coursematerial` # Business API Design Specification - `Delete Coursematerial` 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 `deleteCourseMaterial` 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 `deleteCourseMaterial` Business API is designed to handle a `delete` operation on the `CourseMaterial` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor deletes course material. Only course's tutor or admin can delete. ## 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 `coursematerial-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 `deleteCourseMaterial` Business API includes a REST controller that can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` 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 `deleteCourseMaterial` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteCourseMaterial` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseMaterialId` | `ID` | `Yes` | `-` | `urlpath` | `courseMaterialId` | | **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 `deleteCourseMaterial` 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: `[tutor, 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.courseMaterialId},{isActive:true}]}), {"path":"services[1].businessLogic[11].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 `deleteCourseMaterial` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'DELETE', url: `/v1/coursematerials/${courseMaterialId}`, 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 **`courseMaterial`** 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": "courseMaterial", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Coursematerial` # Business API Design Specification - `Get Coursematerial` 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 `getCourseMaterial` 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 `getCourseMaterial` Business API is designed to handle a `get` operation on the `CourseMaterial` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get course material. Only accessible by tutor owner or enrolled student or admin. ## 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 `coursematerial-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 `getCourseMaterial` Business API includes a REST controller that can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` 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 `getCourseMaterial` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getCourseMaterial` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseMaterialId` | `ID` | `Yes` | `-` | `urlpath` | `courseMaterialId` | | **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 `getCourseMaterial` 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: `[user, student, tutor, 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.", `id`,`coursePackId`,`fileUrl`,`fileType`,`title`,`description`,`linkUrl` ## 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.courseMaterialId},{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 `getCourseMaterial` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'GET', url: `/v1/coursematerials/${courseMaterialId}`, 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 **`courseMaterial`** 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": "courseMaterial", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` --- ### Business API Design Specification - `List Coursematerials` # Business API Design Specification - `List Coursematerials` 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 `listCourseMaterials` 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 `listCourseMaterials` Business API is designed to handle a `list` operation on the `CourseMaterial` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List course materials for a coursePack. Only accessible to enrolled students, tutor owner, or admin. ## 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 `coursematerials-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 `listCourseMaterials` Business API includes a REST controller that can be triggered via the following route: `/v1/coursematerials` 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 `listCourseMaterials` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listCourseMaterials` 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 `listCourseMaterials` 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: `[user, student, tutor, 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.", `id`,`coursePackId`,`fileUrl`,`fileType`,`title`,`description`,`linkUrl` ## 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 {$and:[this.materialWhereClause,{isActive:true}]} ``` **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:[{$and:[this.materialWhereClause,{isActive:true}]},{isActive:true}]}), {"path":"services[1].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). [ title asc ] **List Group By** Grouping definitions for the result set. This is typically used for visual or report-based grouping. List is grouped by the followinf field(s) : [ fileType ] **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] Action : computeMaterialWhereClause **Action Type**: `FunctionCallAction` ```js class Api { async computeMaterialWhereClause() { try { return await runMScript( () => (async () => await LIB.getAllowedMaterialWhereClause( this.session.userId, this.session.roleId, ))(), { path: "services[1].businessLogic[13].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error( "Error in FunctionCallAction computeMaterialWhereClause:", err, ); throw err; } } } ``` --- ### [7] 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` --- ### [8] 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` --- ### [9] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [10] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [11] 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 `listCourseMaterials` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coursematerials** ```js axios({ method: 'GET', url: '/v1/coursematerials', 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 **`courseMaterials`** 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": "courseMaterials", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseMaterials": [ { "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Coursecategory` # Business API Design Specification - `Create Coursecategory` 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 `createCourseCategory` 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 `createCourseCategory` Business API is designed to handle a `create` operation on the `CourseCategory` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin creates new course category/subject tag. ## 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 `coursecategory-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 `createCourseCategory` Business API includes a REST controller that can be triggered via the following route: `/v1/coursecategories` 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 `createCourseCategory` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createCourseCategory` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseCategoryId` | `ID` | `No` | `-` | `body` | `courseCategoryId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `name` | `String` | `Yes` | `-` | `body` | `name` | | **Description:** | Unique category/subject name. | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Category description. | | | | | | | | | | | | | `icon` | `String` | `No` | `-` | `body` | `icon` | | **Description:** | Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) | | | | | | | | | | | | ### 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 `createCourseCategory` 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** *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.courseCategoryId, name: this.name, description: this.description, icon: this.icon, 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 `createCourseCategory` api has got 3 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/coursecategories** ```js axios({ method: 'POST', url: '/v1/coursecategories', data: { name:"String", description:"Text", icon:"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 **`courseCategory`** 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": "courseCategory", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Coursecategory` # Business API Design Specification - `Update Coursecategory` 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 `updateCourseCategory` 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 `updateCourseCategory` Business API is designed to handle a `update` operation on the `CourseCategory` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin updates course category/subject tag. ## 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 `coursecategory-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 `updateCourseCategory` Business API includes a REST controller that can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` 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 `updateCourseCategory` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateCourseCategory` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseCategoryId` | `ID` | `Yes` | `-` | `urlpath` | `courseCategoryId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `name` | `String` | `No` | `-` | `body` | `name` | | **Description:** | Unique category/subject name. | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Category description. | | | | | | | | | | | | | `icon` | `String` | `No` | `-` | `body` | `icon` | | **Description:** | Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) | | | | | | | | | | | | ### 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 `updateCourseCategory` 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]` --- ## 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.courseCategoryId},{isActive:true}]}), {"path":"services[1].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 { name: this.name, description: this.description, icon: this.icon, } ``` ## 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 `updateCourseCategory` api has got 4 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | | name | String | false | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/coursecategories/:courseCategoryId** ```js axios({ method: 'PATCH', url: `/v1/coursecategories/${courseCategoryId}`, data: { name:"String", description:"Text", icon:"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 **`courseCategory`** 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": "courseCategory", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Coursecategory` # Business API Design Specification - `Delete Coursecategory` 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 `deleteCourseCategory` 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 `deleteCourseCategory` Business API is designed to handle a `delete` operation on the `CourseCategory` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin deletes a course category/subject tag. Only admin allowed. ## 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 `coursecategory-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 `deleteCourseCategory` Business API includes a REST controller that can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` 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 `deleteCourseCategory` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteCourseCategory` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `courseCategoryId` | `ID` | `Yes` | `-` | `urlpath` | `courseCategoryId` | | **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 `deleteCourseCategory` 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]` --- ## 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.courseCategoryId},{isActive:true}]}), {"path":"services[1].businessLogic[16].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 `deleteCourseCategory` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/coursecategories/:courseCategoryId** ```js axios({ method: 'DELETE', url: `/v1/coursecategories/${courseCategoryId}`, 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 **`courseCategory`** 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": "courseCategory", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Coursecategory` # Business API Design Specification - `Get Coursecategory` 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 `getCourseCategory` 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 `getCourseCategory` Business API is designed to handle a `get` operation on the `CourseCategory` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Publicly fetch a course category/subject by name. No login required. ## 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 `coursecategory-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 `getCourseCategory` Business API includes a REST controller that can be triggered via the following route: `/v1/coursecategories/:name` 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 `getCourseCategory` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getCourseCategory` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `name` | `String` | `Yes` | `-` | `urlpath` | `name` | | **Description:** | Unique category/subject name.. 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 `getCourseCategory` 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: `[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.", `name`,`description` ## 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:[{name:{"$eq":this.name}},{isActive:true}]}), {"path":"services[1].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 `getCourseCategory` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.params?.["name"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coursecategories/:name** ```js axios({ method: 'GET', url: `/v1/coursecategories/${name}`, 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 **`courseCategory`** 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": "courseCategory", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseCategory": { "isActive": true } } ``` --- ### Business API Design Specification - `List Coursecategories` # Business API Design Specification - `List Coursecategories` 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 `listCourseCategories` 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 `listCourseCategories` Business API is designed to handle a `list` operation on the `CourseCategory` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Publicly list all course categories/subjects for navigation, filtering, and display. No login required. ## 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 `coursecategories-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 `listCourseCategories` Business API includes a REST controller that can be triggered via the following route: `/v1/coursecategories` 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 `listCourseCategories` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listCourseCategories` 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 `listCourseCategories` 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: `[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.", `id`,`name`,`description` ## 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[18].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). [ name 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 `listCourseCategories` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/coursecategories** ```js axios({ method: 'GET', url: '/v1/coursecategories', 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 **`courseCategories`** 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": "courseCategories", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseCategories": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `On Tutorapplicationreviewed` # Business API Design Specification - `On Tutorapplicationreviewed` 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 `onTutorApplicationReviewed` 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 `onTutorApplicationReviewed` Business API is designed to handle a `create` operation on the `TutorProfile` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description ## API Frontend Description By The Backend Architect Kafka event handler that creates tutor profile when auth service approves a tutor application. Listens to tutorhub-auth-service-tutorapplication-reviewed topic. ## 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 `tutorapplicationreviewed-oned` 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 `onTutorApplicationReviewed` Business API includes a REST controller that can be triggered via the following route: `/v1/ontutorapplicationreviewed` 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. ### Kafka Controller The `onTutorApplicationReviewed` Business API includes a Kafka controller, which can be triggered by sending a message to the configured Kafka topic. This enables your API to participate in an event-driven architecture. The following topic is listened to in order to trigger the `onTutorApplicationReviewed` Business API: `tutorhub-auth-service-tutorapplication-reviewed` All parameters must be provided as body parameters in the message JSON payload, regardless of their HTTP location configuration, which applies only to 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 `onTutorApplicationReviewed` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `onTutorApplicationReviewed` Business API has 9 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `No` | `-` | `body` | `tutorProfileId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `tutorId` | `ID` | `Yes` | `-` | `body` | `tutorId` | | **Description:** | - | | | | | | | | | | | | | `certifications` | `String` | `No` | `-` | `body` | `certifications` | | **Description:** | Tutor's certifications (list of certificates, degrees, etc.). | | | | | | | | | | | | | `experience` | `Text` | `No` | `-` | `body` | `experience` | | **Description:** | Brief experience summary or bio. | | | | | | | | | | | | | `subjects` | `String` | `No` | `-` | `body` | `subjects` | | **Description:** | Areas of expertise/subjects offered for teaching. | | | | | | | | | | | | | `bio` | `Text` | `No` | `-` | `body` | `bio` | | **Description:** | Optional full-length bio/description. | | | | | | | | | | | | | `profilePhoto` | `String` | `No` | `-` | `body` | `profilePhoto` | | **Description:** | Public profile photo URL (may be external or uploaded). | | | | | | | | | | | | | `profileStatus` | `Enum` | `Yes` | `-` | `body` | `profileStatus` | | **Description:** | - | | | | | | | | | | | | | `displayName` | `String` | `No` | `-` | `body` | `displayName` | | **Description:** | Tutor's display name, copied from auth user fullname at profile creation. | | | | | | | | | | | | ### 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 `onTutorApplicationReviewed` 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 { tutorId: runMScript(() => (this.data && this.data.user ? this.data.user.id : null), {"path":"services[1].businessLogic[19].dataClause.customData[0].value"}), bio: runMScript(() => (this.data && this.data.user ? (this.data.user.bio || '') : ''), {"path":"services[1].businessLogic[19].dataClause.customData[1].value"}), experience: runMScript(() => (this.data && this.data.user ? (this.data.user.qualifications || '') : ''), {"path":"services[1].businessLogic[19].dataClause.customData[2].value"}), certifications: runMScript(() => (this.data && this.data.user && this.data.user.certifications ? [this.data.user.certifications] : []), {"path":"services[1].businessLogic[19].dataClause.customData[3].value"}), subjects: runMScript(() => (this.data && this.data.user ? (this.data.user.specializations || []) : []), {"path":"services[1].businessLogic[19].dataClause.customData[4].value"}), profileStatus: runMScript(() => ('approved'), {"path":"services[1].businessLogic[19].dataClause.customData[5].value"}), isActive: runMScript(() => (true), {"path":"services[1].businessLogic[19].dataClause.customData[6].value"}), displayName: runMScript(() => (this.data && this.data.user ? (this.data.user.fullname || '') : ''), {"path":"services[1].businessLogic[19].dataClause.customData[7].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.tutorProfileId, tutorId: runMScript(() => (this.data && this.data.user ? this.data.user.id : null), {"path":"services[1].businessLogic[19].dataClause.customData[0].value"}), certifications: runMScript(() => (this.data && this.data.user && this.data.user.certifications ? [this.data.user.certifications] : []), {"path":"services[1].businessLogic[19].dataClause.customData[3].value"}), experience: runMScript(() => (this.data && this.data.user ? (this.data.user.qualifications || '') : ''), {"path":"services[1].businessLogic[19].dataClause.customData[2].value"}), subjects: runMScript(() => (this.data && this.data.user ? (this.data.user.specializations || []) : []), {"path":"services[1].businessLogic[19].dataClause.customData[4].value"}), bio: runMScript(() => (this.data && this.data.user ? (this.data.user.bio || '') : ''), {"path":"services[1].businessLogic[19].dataClause.customData[1].value"}), profilePhoto: this.profilePhoto, profileStatus: runMScript(() => ('approved'), {"path":"services[1].businessLogic[19].dataClause.customData[5].value"}), displayName: runMScript(() => (this.data && this.data.user ? (this.data.user.fullname || '') : ''), {"path":"services[1].businessLogic[19].dataClause.customData[7].value"}), isActive: runMScript(() => (true), {"path":"services[1].businessLogic[19].dataClause.customData[6].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 `onTutorApplicationReviewed` api has got 8 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | true | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/ontutorapplicationreviewed** ```js axios({ method: 'POST', url: '/v1/ontutorapplicationreviewed', data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"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 **`tutorProfile`** 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": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ## Service Library - `tutorCatalog` # Service Library - `tutorCatalog` This document provides a complete reference of the custom code library for the `tutorCatalog` 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/")`. ### `getTutorProfileIdsBySessionUserId.js` ```js module.exports = async function getTutorProfileIdsBySessionUserId(userId) { if (!userId) return []; const db = require("dbLayer"); const items = await db.getTutorProfileListByMQuery({ tutorId: userId, isActive: true }); return items.map(i => i.id); } ``` ### `getCoursePackIdsBySessionUserId.js` ```js module.exports = async function getCoursePackIdsBySessionUserId(userId) { if (!userId) return []; const tutorProfileIds = await LIB.getTutorProfileIdsBySessionUserId(userId); if (!tutorProfileIds.length) return []; const db = require("dbLayer"); const packs = await db.getCoursePackListByMQuery({ tutorProfileId: { $in: tutorProfileIds }, isActive: true }); return packs.map(p => p.id); } ``` ### `isMaterialViewAllowedBySession.js` ```js module.exports = async function isMaterialViewAllowedBySession(courseMaterialId, userId, roleId) { if (!userId || !courseMaterialId) return false; if (roleId === "admin") return true; const MODELS = require("models"); const cm = await MODELS.CourseMaterial.findOne({ where: { id: courseMaterialId, isActive: true } }); if (!cm) return false; const pack = await MODELS.CoursePack.findOne({ where: { id: cm.coursePackId, isActive: true } }); if (!pack) return false; if (roleId === "tutor") { const tprofiles = await MODELS.TutorProfile.findAll({ where: { tutorId: userId, isActive: true } }); if (tprofiles.some(tpf => tpf.id === pack.tutorProfileId)) return true; } if (roleId === "student") { const { fetchRemoteListByMQuery } = require("serviceCommon"); const enrolls = await fetchRemoteListByMQuery("enrollmentManagement:enrollment", { studentId: userId, coursePackId: pack.id, isActive: true, enrollmentStatus: "active" }, 0, 1); if (enrolls && enrolls.length > 0) return true; } return false; } ``` ### `getAllowedMaterialWhereClause.js` ```js module.exports = async function getAllowedMaterialWhereClause(userId, roleId) { if (!userId) return { id: null }; if (roleId === "admin") return {}; const db = require("dbLayer"); if (roleId === "tutor") { const tprofiles = await db.getTutorProfileListByMQuery({ tutorId: userId, isActive: true }); if (!tprofiles.length) return { id: null }; const packs = await db.getCoursePackListByMQuery({ tutorProfileId: { $in: tprofiles.map(p => p.id) }, isActive: true }); const accessiblePackIds = packs.map(p => p.id); if (!accessiblePackIds.length) return { id: null }; return { coursePackId: { $in: accessiblePackIds } }; } if (roleId === "student") { const { fetchRemoteListByMQuery } = require("serviceCommon"); const enrolls = await fetchRemoteListByMQuery("enrollmentManagement:enrollment", { studentId: userId, isActive: true, enrollmentStatus: "active" }, 0, 100); const enrolledPackIds = enrolls ? enrolls.map(e => e.coursePackId) : []; if (!enrolledPackIds.length) return { id: null }; return { coursePackId: { $in: enrolledPackIds } }; } return { id: null }; } ``` ### `checkCoursePackActiveEnrollments.js` ```js module.exports = async function checkCoursePackActiveEnrollments(coursePackId) { if (!coursePackId) return { hasActiveEnrollments: false, count: 0, enrollments: [] }; try { // Use interservice HTTP call to enrollmentManagement's internal fetch endpoint // This reads from the DB (source of truth), not ES which may be stale const axios = require('axios'); const { getServiceSecret } = require('common'); // In preview, all services share the same base host with different routes const baseUrl = process.env.ENROLLMENTMANAGEMENT_API_URL || (process.env.PREVIEW_BASE_URL ? process.env.PREVIEW_BASE_URL + '/enrollmentmanagement-api' : null); // Fallback: use the _fetchList internal endpoint via M2M or query ES if (!baseUrl) { // Try ES as fallback const { elasticClient } = require('common'); const res = await elasticClient.search({ index: 'tutorhub_enrollment', body: { query: { bool: { must: [ { term: { coursePackId: coursePackId } }, { term: { enrollmentStatus: 'active' } }, { term: { isActive: true } } ] } }, size: 100 } }); const enrollments = res.hits.hits.map(h => h._source); return { hasActiveEnrollments: enrollments.length > 0, count: enrollments.length, enrollments }; } const serviceSecret = getServiceSecret ? getServiceSecret() : process.env.SERVICE_SECRET_KEY; const url = `${baseUrl}/m2m/getEnrollmentListByMQuery`; const response = await axios.post(url, { query: { coursePackId, enrollmentStatus: 'active', isActive: true } }, { headers: { 'Content-Type': 'application/json', ...(serviceSecret ? { 'x-service-secret': serviceSecret } : {}) }, timeout: 10000 }); const enrollments = response.data || []; return { hasActiveEnrollments: enrollments.length > 0, count: enrollments.length, enrollments }; } catch (err) { console.log('ERROR in checkCoursePackActiveEnrollments:', err.message); // FAIL SAFE: if we can't check, assume there ARE enrollments to prevent accidental deletion return { hasActiveEnrollments: true, count: -1, enrollments: [], error: err.message }; } } ``` ### `triggerAdminCourseRemovalCascade.js` ```js module.exports = async function triggerAdminCourseRemovalCascade(coursePackId, removalReason, enrollmentCheck, session) { const { fetchRemoteListByMQuery, callRemoteApi } = require('serviceCommon'); const { elasticClient } = require('common'); if (!enrollmentCheck || !enrollmentCheck.hasActiveEnrollments) { return { processed: 0, total: 0, refunds: [] }; } const enrollments = enrollmentCheck.enrollments || []; const results = { processed: 0, total: enrollments.length, refunds: [], errors: [] }; for (const enrollment of enrollments) { try { // Fetch lesson slots to calculate completion percentage const slotIds = enrollment.lessonSlotIds || []; let completedCount = 0; let totalSlots = slotIds.length; if (totalSlots > 0) { try { const slotsRes = await elasticClient.search({ index: 'tutorhub_lessonslot', body: { query: { terms: { id: slotIds } }, _source: ['id', 'status'], size: 500 } }); const slots = slotsRes.hits.hits.map(h => h._source); completedCount = slots.filter(s => s.status === 'completed').length; } catch (esErr) { console.log('Warning: ES slot lookup failed, assuming 0 completed:', esErr.message); } } // Calculate pro-rata refund amount const completionRatio = totalSlots > 0 ? completedCount / totalSlots : 0; let refundAmount = 0; let refundNote = ''; if (completionRatio === 0) { refundAmount = enrollment.totalAmount; refundNote = 'Full refund - no lessons completed'; } else if (completionRatio <= 0.5) { const unusedSlots = totalSlots - completedCount; refundAmount = Math.round((unusedSlots / totalSlots) * enrollment.totalAmount * 100) / 100; refundNote = `Pro-rata refund: ${completedCount}/${totalSlots} lessons completed, refunding ${unusedSlots} unused lessons`; } else { refundAmount = 0; refundNote = `No refund: ${completedCount}/${totalSlots} lessons completed (over 50%)`; } // Fetch student data for email notifications let studentData = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) studentData = studentRes.hits.hits[0]._source; } catch (e) { console.log('Warning: student lookup failed:', e.message); } if (refundAmount > 0) { try { await callRemoteApi('enrollmentManagement', 'adminRefundEnrollment', { enrollmentId: enrollment.id, reason: `Course removed by admin. Reason: ${removalReason || 'No reason provided'}. ${refundNote}` }, session); } catch (refundErr) { console.log('Warning: adminRefundEnrollment failed for', enrollment.id, ':', refundErr.message); results.errors.push({ enrollmentId: enrollment.id, error: refundErr.message }); } } else { try { await callRemoteApi('enrollmentManagement', 'cancelEnrollment', { enrollmentId: enrollment.id, reason: `Course removed by admin. Reason: ${removalReason || 'No reason provided'}. ${refundNote}` }, session); } catch (cancelErr) { console.log('Warning: cancelEnrollment failed for', enrollment.id, ':', cancelErr.message); results.errors.push({ enrollmentId: enrollment.id, error: cancelErr.message }); } } results.refunds.push({ enrollmentId: enrollment.id, studentId: enrollment.studentId, studentEmail: studentData ? studentData.email : null, studentName: studentData ? studentData.fullname : null, totalAmount: enrollment.totalAmount, currency: enrollment.currency || 'USD', refundAmount, completedLessons: completedCount, totalLessons: totalSlots, note: refundNote }); results.processed++; } catch (err) { results.errors.push({ enrollmentId: enrollment.id, error: err.message }); } } // Publish individual Kafka events per student for email notifications try { const { sendMessageToKafka } = require('common'); const db = require('dbLayer'); const coursePack = await db.getCoursePackById(coursePackId); const courseTitle = coursePack ? coursePack.title : 'Unknown Course'; for (const refund of results.refunds) { if (refund.studentEmail) { await sendMessageToKafka('tutorhub-tutorcatalog-service-coursepack-removed-by-admin', { coursePackId, courseTitle, removalReason: removalReason || 'No reason provided', student: { email: refund.studentEmail, fullname: refund.studentName }, refundAmount: refund.refundAmount, totalAmount: refund.totalAmount, currency: refund.currency, completedLessons: refund.completedLessons, totalLessons: refund.totalLessons, refundNote: refund.note, removedAt: new Date().toISOString() }); } } } catch (kafkaErr) { console.log('Warning: failed to publish course removal events:', kafkaErr.message); } return results; } ``` --- *This document was generated from the service library configuration and should be kept in sync with design changes.* --- # CourseScheduling Service ## Service Design Specification # Service Design Specification **tutorhub-coursescheduling-service** documentation **Version:** `1.0.48` ## Scope This document provides a structured architectural overview of the `courseScheduling` 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. ## `CourseScheduling` Service Settings Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). ### Service Overview This service is configured to listen for HTTP requests on port `3002`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-coursescheduling-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/coursescheduling-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/coursescheduling-api` * **Production:** `https://tutorhub.mindbricks.co/coursescheduling-api` ### Authentication & Security - **Login Required**: Yes This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-coursescheduling-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 | |-------------|-------------|---------------| | `availability` | Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. | accessPrivate | | `lessonSlot` | No description | accessPrivate | | `preliminaryMeeting` | Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. | accessPrivate | ## availability Data Object ### Object Overview **Description:** Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. 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 - **uniqueTutorDayAvailability**: [tutorProfileId, dayOfWeek, startTime, endTime] 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 | |----------|------|----------|-------------| | `tutorProfileId` | ID | Yes | FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. | | `dayOfWeek` | Enum | Yes | Day of week: sunday-saturday. | | `startTime` | String | Yes | Start time of window (HH:mm, 24h). | | `endTime` | String | Yes | End time of window (HH:mm, 24h). | | `isRecurring` | Boolean | Yes | If true, this slot recurs weekly. | | `specificDate` | Date | No | Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. | | `teachingMode` | 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. - **tutorProfileId**: '00000000-0000-0000-0000-000000000000' - **dayOfWeek**: monday - **startTime**: 'default' - **endTime**: 'default' - **isRecurring**: true - **teachingMode**: "online" ### Constant Properties `tutorProfileId` 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 `tutorProfileId` `dayOfWeek` `startTime` `endTime` `isRecurring` `specificDate` `teachingMode` 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. - **dayOfWeek**: [sunday, monday, tuesday, wednesday, thursday, friday, saturday] - **teachingMode**: [online, faceToFace, both] ### Elastic Search Indexing `tutorProfileId` `dayOfWeek` `startTime` `endTime` `isRecurring` `specificDate` `teachingMode` 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 `tutorProfileId` `specificDate` 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 `tutorProfileId` 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. - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Filter Properties `teachingMode` 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. - **teachingMode**: Enum has a filter named `teachingMode` ## lessonSlot 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. ### Composite Indexes - **uniqueCoursePackSlot**: [coursePackId, scheduledDate, scheduledTime] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. | | `studentId` | ID | No | FK to auth:user (student). Set on booking. Nullable when open (free). | | `scheduledDate` | Date | Yes | Date for the lesson slot (yyyy-mm-dd). | | `scheduledTime` | String | Yes | Start time of lesson (HH:mm 24h). | | `status` | Enum | Yes | State of lesson slot (free, booked, completed, canceled). | | `locationType` | Enum | No | - | | `locationDetails` | String | No | Optional: Location address/details; editable after booking by either party. | | `sessionMode` | Enum | Yes | Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. | | `meetLink` | String | No | Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. | * 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. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **scheduledDate**: new Date() - **scheduledTime**: 'default' - **status**: free - **locationType**: online - **sessionMode**: "online" ### Constant Properties `coursePackId` `scheduledDate` `scheduledTime` 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 `coursePackId` `studentId` `scheduledDate` `scheduledTime` `status` `locationType` `locationDetails` `sessionMode` `meetLink` 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**: [free, booked, completed, canceled] - **locationType**: [online, studentHome, tutorHome, other] - **sessionMode**: [online, faceToFace] ### Elastic Search Indexing `coursePackId` `studentId` `scheduledDate` `scheduledTime` `status` `locationType` `sessionMode` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `coursePackId` `studentId` `scheduledDate` `scheduledTime` `status` `sessionMode` 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 `coursePackId` `studentId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: No ### Filter Properties `coursePackId` `studentId` `status` `sessionMode` 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. - **coursePackId**: ID has a filter named `coursePackId` - **studentId**: ID has a filter named `studentId` - **status**: Enum has a filter named `status` - **sessionMode**: Enum has a filter named `sessionMode` ## preliminaryMeeting Data Object ### Object Overview **Description:** Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. 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 - **uniqueCoursePackStudentMeeting**: [coursePackId, studentId] 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 | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to tutorCatalog:coursePack (the advanced course) | | `studentId` | ID | Yes | FK to auth:user (student who requested). | | `scheduledDatetime` | Date | No | Datetime for screening meeting; may be null until both parties agree. | | `tutorDecision` | Enum | Yes | - | | `comments` | String | No | Optional field for tutor to provide comments/notes about screening result. | | `meetingLink` | String | No | Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. | * 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. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **studentId**: '00000000-0000-0000-0000-000000000000' - **tutorDecision**: "pending" ### Constant Properties `coursePackId` `studentId` 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 `coursePackId` `studentId` `scheduledDatetime` `tutorDecision` `comments` `meetingLink` 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. - **tutorDecision**: [pending, approved, rejected] ### Elastic Search Indexing `coursePackId` `studentId` `scheduledDatetime` `tutorDecision` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `coursePackId` `studentId` `tutorDecision` 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 `coursePackId` `studentId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ## Business Logic courseScheduling has got 14 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Create Availability](/document/businessLogic/createavailability) * [Update Availability](/document/businessLogic/updateavailability) * [Delete Availability](/document/businessLogic/deleteavailability) * [Get Availability](/document/businessLogic/getavailability) * [List Availabilities](/document/businessLogic/listavailabilities) * [Create Lessonslot](/document/businessLogic/createlessonslot) * [Update Lessonslot](/document/businessLogic/updatelessonslot) * [Delete Lessonslot](/document/businessLogic/deletelessonslot) * [Get Lessonslot](/document/businessLogic/getlessonslot) * [List Lessonslots](/document/businessLogic/listlessonslots) * [Create Preliminarymeeting](/document/businessLogic/createpreliminarymeeting) * [Update Preliminarymeeting](/document/businessLogic/updatepreliminarymeeting) * [Get Preliminarymeeting](/document/businessLogic/getpreliminarymeeting) * [List Preliminarymeetings](/document/businessLogic/listpreliminarymeetings) ## Service Library ### Functions #### validateSlotAgainstAvailability.js ```js module.exports = function validateSlotAgainstAvailability(availabilities, scheduledDate, scheduledTime) { if (!availabilities || availabilities.length === 0) { return { valid: false, error: 'No tutor availability found for this course.' }; } const dateStr = (scheduledDate || '').split('T')[0]; const d = new Date(dateStr + 'T00:00:00Z'); if (isNaN(d.getTime())) return { valid: false, error: 'Invalid scheduled date.' }; const dayNames = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday']; const slotDay = dayNames[d.getUTCDay()]; const slotHour = parseInt((scheduledTime || '').split(':')[0], 10); const slotMin = parseInt((scheduledTime || '').split(':')[1], 10) || 0; const slotMinutes = slotHour * 60 + slotMin; for (const av of availabilities) { if (av.dayOfWeek !== slotDay) continue; if (!av.isRecurring && av.specificDate) { const avDate = (av.specificDate || '').split('T')[0]; if (avDate !== dateStr) continue; } const [sh, sm] = (av.startTime || '').split(':').map(Number); const [eh, em] = (av.endTime || '').split(':').map(Number); const startMin = sh * 60 + (sm || 0); const endMin = eh * 60 + (em || 0); if (slotMinutes >= startMin && slotMinutes < endMin) { return { valid: true, error: null }; } } return { valid: false, error: 'No matching availability for ' + slotDay + ' at ' + scheduledTime + '.' }; }; ``` --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## tutorhub-coursescheduling-service **Version:** `1.0.48` Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). ## 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 CourseScheduling Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our CourseScheduling Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the CourseScheduling Service via HTTP requests for purposes such as creating, updating, deleting and querying CourseScheduling 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 CourseScheduling 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 CourseScheduling 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 | tutorhub-access-token| | Cookie | tutorhub-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 CourseScheduling 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 CourseScheduling service. This service is configured to listen for HTTP requests on port `3002`, 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://tutorhub.prw.mindbricks.com/coursescheduling-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/coursescheduling-api` * **Production:** `https://tutorhub.mindbricks.co/coursescheduling-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 CourseScheduling 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 `CourseScheduling` 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 `CourseScheduling` 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 `CourseScheduling` 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 CourseScheduling 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. ### Availability resource *Resource Definition* : Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. *Availability Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **tutorProfileId** | ID | | | *FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit.* | | **dayOfWeek** | Enum | | | *Day of week: sunday-saturday.* | | **startTime** | String | | | *Start time of window (HH:mm, 24h).* | | **endTime** | String | | | *End time of window (HH:mm, 24h).* | | **isRecurring** | Boolean | | | *If true, this slot recurs weekly.* | | **specificDate** | Date | | | *Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots.* | | **teachingMode** | Enum | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### dayOfWeek Enum Property *Property Definition* : Day of week: sunday-saturday.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **sunday** | `"sunday""` | 0 | | **monday** | `"monday""` | 1 | | **tuesday** | `"tuesday""` | 2 | | **wednesday** | `"wednesday""` | 3 | | **thursday** | `"thursday""` | 4 | | **friday** | `"friday""` | 5 | | **saturday** | `"saturday""` | 6 | ##### teachingMode Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **online** | `"online""` | 0 | | **faceToFace** | `"faceToFace""` | 1 | | **both** | `"both""` | 2 | ### LessonSlot resource *LessonSlot Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view.* | | **studentId** | ID | | | *FK to auth:user (student). Set on booking. Nullable when open (free).* | | **scheduledDate** | Date | | | *Date for the lesson slot (yyyy-mm-dd).* | | **scheduledTime** | String | | | *Start time of lesson (HH:mm 24h).* | | **status** | Enum | | | *State of lesson slot (free, booked, completed, canceled).* | | **locationType** | Enum | | | ** | | **locationDetails** | String | | | *Optional: Location address/details; editable after booking by either party.* | | **sessionMode** | Enum | | | *Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails.* | | **meetLink** | String | | | *Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions.* | #### 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* : State of lesson slot (free, booked, completed, canceled).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **free** | `"free""` | 0 | | **booked** | `"booked""` | 1 | | **completed** | `"completed""` | 2 | | **canceled** | `"canceled""` | 3 | ##### locationType Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **online** | `"online""` | 0 | | **studentHome** | `"studentHome""` | 1 | | **tutorHome** | `"tutorHome""` | 2 | | **other** | `"other""` | 3 | ##### sessionMode Enum Property *Property Definition* : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **online** | `"online""` | 0 | | **faceToFace** | `"faceToFace""` | 1 | ### PreliminaryMeeting resource *Resource Definition* : Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. *PreliminaryMeeting Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to tutorCatalog:coursePack (the advanced course)* | | **studentId** | ID | | | *FK to auth:user (student who requested).* | | **scheduledDatetime** | Date | | | *Datetime for screening meeting; may be null until both parties agree.* | | **tutorDecision** | Enum | | | ** | | **comments** | String | | | *Optional field for tutor to provide comments/notes about screening result.* | | **meetingLink** | String | | | *Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### tutorDecision Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ## Business Api ### `Create Availability` API **[Default create API]** — This is the designated default `create` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor creates available time window for teaching. Only owner tutor or admin. **Rest Route** The `createAvailability` API REST controller can be triggered via the following route: `/v1/availabilities` **Rest Request Parameters** The `createAvailability` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | dayOfWeek | Enum | true | request.body?.["dayOfWeek"] | | startTime | String | true | request.body?.["startTime"] | | endTime | String | true | request.body?.["endTime"] | | isRecurring | Boolean | true | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | true | request.body?.["teachingMode"] | **tutorProfileId** : FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. **dayOfWeek** : Day of week: sunday-saturday. **startTime** : Start time of window (HH:mm, 24h). **endTime** : End time of window (HH:mm, 24h). **isRecurring** : If true, this slot recurs weekly. **specificDate** : Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. **teachingMode** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/availabilities** ```js axios({ method: 'POST', url: '/v1/availabilities', data: { tutorProfileId:"ID", dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Availability` API **[Default update API]** — This is the designated default `update` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates an availability record (only own, or admin). **Rest Route** The `updateAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `updateAvailability` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | | dayOfWeek | Enum | false | request.body?.["dayOfWeek"] | | startTime | String | false | request.body?.["startTime"] | | endTime | String | false | request.body?.["endTime"] | | isRecurring | Boolean | false | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | false | request.body?.["teachingMode"] | **availabilityId** : This id paremeter is used to select the required data object that will be updated **dayOfWeek** : Day of week: sunday-saturday. **startTime** : Start time of window (HH:mm, 24h). **endTime** : End time of window (HH:mm, 24h). **isRecurring** : If true, this slot recurs weekly. **specificDate** : Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. **teachingMode** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/availabilities/:availabilityId** ```js axios({ method: 'PATCH', url: `/v1/availabilities/${availabilityId}`, data: { dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Availability` API **[Default delete API]** — This is the designated default `delete` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes an availability record (only own, or admin). **Rest Route** The `deleteAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `deleteAvailability` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | **availabilityId** : 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/availabilities/:availabilityId** ```js axios({ method: 'DELETE', url: `/v1/availabilities/${availabilityId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Availability` API **[Default get API]** — This is the designated default `get` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one availability by id (tutor/owner or admin only). **Rest Route** The `getAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `getAvailability` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | **availabilityId** : 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/availabilities/:availabilityId** ```js axios({ method: 'GET', url: `/v1/availabilities/${availabilityId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Availabilities` API **Rest Route** The `listAvailabilities` API REST controller can be triggered via the following route: `/v1/listavailabilities/:tutorProfileId` **Rest Request Parameters** The `listAvailabilities` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | **tutorProfileId** : FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit.. The parameter is used to query data. **Filter Parameters** The `listAvailabilities` api supports 1 optional filter parameter for filtering list results: **teachingMode** (`Enum`): Filter by teachingMode - Single: `?teachingMode=` (case-insensitive) - Multiple: `?teachingMode=&teachingMode=` - Null: `?teachingMode=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/listavailabilities/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/listavailabilities/${tutorProfileId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // teachingMode: '' // Filter by teachingMode } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availabilities", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "availabilities": [ { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Lessonslot` API **Rest Route** The `createLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots` **Rest Request Parameters** The `createLessonSlot` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | false | request.body?.["studentId"] | | scheduledDate | Date | true | request.body?.["scheduledDate"] | | scheduledTime | String | true | request.body?.["scheduledTime"] | | status | Enum | true | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | true | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | **coursePackId** : FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. **studentId** : FK to auth:user (student). Set on booking. Nullable when open (free). **scheduledDate** : Date for the lesson slot (yyyy-mm-dd). **scheduledTime** : Start time of lesson (HH:mm 24h). **status** : State of lesson slot (free, booked, completed, canceled). **locationType** : **locationDetails** : Optional: Location address/details; editable after booking by either party. **sessionMode** : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. **meetLink** : Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/lessonslots** ```js axios({ method: 'POST', url: '/v1/lessonslots', data: { coursePackId:"ID", studentId:"ID", scheduledDate:"Date", scheduledTime:"String", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Lessonslot` API **[Default update API]** — This is the designated default `update` API for the `lessonSlot` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update lesson slot status/location. Tutor can edit any of their coursePack's slots; student can update their own booked slot location (if booked). Admin has override right. **Rest Route** The `updateLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `updateLessonSlot` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | | studentId | ID | false | request.body?.["studentId"] | | status | Enum | false | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | false | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | **lessonSlotId** : This id paremeter is used to select the required data object that will be updated **studentId** : FK to auth:user (student). Set on booking. Nullable when open (free). **status** : State of lesson slot (free, booked, completed, canceled). **locationType** : **locationDetails** : Optional: Location address/details; editable after booking by either party. **sessionMode** : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. **meetLink** : Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'PATCH', url: `/v1/lessonslots/${lessonSlotId}`, data: { studentId:"ID", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Lessonslot` API **[Default delete API]** — This is the designated default `delete` API for the `lessonSlot` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor can remove their own slot if free/booked. Admin can remove any. (Student may not delete). **Rest Route** The `deleteLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `deleteLessonSlot` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | **lessonSlotId** : 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/lessonslots/:lessonSlotId** ```js axios({ method: 'DELETE', url: `/v1/lessonslots/${lessonSlotId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Lessonslot` API **Rest Route** The `getLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `getLessonSlot` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | **lessonSlotId** : 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/lessonslots/:lessonSlotId** ```js axios({ method: 'GET', url: `/v1/lessonslots/${lessonSlotId}`, 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": "lessonSlot", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "isActive": true } } ``` ### `List Lessonslots` API **Rest Route** The `listLessonSlots` API REST controller can be triggered via the following route: `/v1/lessonslots` **Rest Request Parameters** The `listLessonSlots` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/lessonslots** ```js axios({ method: 'GET', url: '/v1/lessonslots', 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": "lessonSlots", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "lessonSlots": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Preliminarymeeting` API **[Default create API]** — This is the designated default `create` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student requests a screening meeting; only created if related coursePack requires screening. **Rest Route** The `createPreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings` **Rest Request Parameters** The `createPreliminaryMeeting` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | true | request.body?.["studentId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | true | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | **coursePackId** : FK to tutorCatalog:coursePack (the advanced course) **studentId** : FK to auth:user (student who requested). **scheduledDatetime** : Datetime for screening meeting; may be null until both parties agree. **tutorDecision** : **comments** : Optional field for tutor to provide comments/notes about screening result. **meetingLink** : Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/preliminarymeetings** ```js axios({ method: 'POST', url: '/v1/preliminarymeetings', data: { coursePackId:"ID", studentId:"ID", scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "coursePack": {}, "tutorProfile": {}, "tutorUser": {}, "student": {} } ``` ### `Update Preliminarymeeting` API **[Default update API]** — This is the designated default `update` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates scheduled date/time, decision, or comments for screening meeting. Only tutor of coursePack or admin can approve/reject/set date; student can only propose initial. **Rest Route** The `updatePreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` **Rest Request Parameters** The `updatePreliminaryMeeting` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | false | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | **preliminaryMeetingId** : This id paremeter is used to select the required data object that will be updated **scheduledDatetime** : Datetime for screening meeting; may be null until both parties agree. **tutorDecision** : **comments** : Optional field for tutor to provide comments/notes about screening result. **meetingLink** : Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'PATCH', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "student": {}, "coursePack": {} } ``` ### `Get Preliminarymeeting` API **[Default get API]** — This is the designated default `get` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single meeting by id: only tutor, student, or admin can access. **Rest Route** The `getPreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` **Rest Request Parameters** The `getPreliminaryMeeting` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | **preliminaryMeetingId** : 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/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'GET', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Preliminarymeetings` API **[Default list API]** — This is the designated default `list` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor can list all meetings for their courses; students see their own; admin sees all. **Rest Route** The `listPreliminaryMeetings` API REST controller can be triggered via the following route: `/v1/preliminarymeetings` **Rest Request Parameters** The `listPreliminaryMeetings` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/preliminarymeetings** ```js axios({ method: 'GET', url: '/v1/preliminarymeetings', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeetings", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "preliminaryMeetings": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "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 ## tutorhub-coursescheduling-service Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). ## 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 `CourseScheduling` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `CourseScheduling` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `CourseScheduling` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `CourseScheduling` 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 `CourseScheduling` 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 availability-created **Event topic**: `tutorhub-coursescheduling-service-dbevent-availability-created` This event is triggered upon the creation of a `availability` 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","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent availability-updated **Event topic**: `tutorhub-coursescheduling-service-dbevent-availability-updated` Activation of this event follows the update of a `availability` data object. The payload contains the updated information under the `availability` attribute, along with the original data prior to update, labeled as `old_availability` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_availability:{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, availability:{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent availability-deleted **Event topic**: `tutorhub-coursescheduling-service-dbevent-availability-deleted` This event announces the deletion of a `availability` 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","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent lessonSlot-created **Event topic**: `tutorhub-coursescheduling-service-dbevent-lessonslot-created` This event is triggered upon the creation of a `lessonSlot` 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","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent lessonSlot-updated **Event topic**: `tutorhub-coursescheduling-service-dbevent-lessonslot-updated` Activation of this event follows the update of a `lessonSlot` data object. The payload contains the updated information under the `lessonSlot` attribute, along with the original data prior to update, labeled as `old_lessonSlot` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_lessonSlot:{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, lessonSlot:{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent lessonSlot-deleted **Event topic**: `tutorhub-coursescheduling-service-dbevent-lessonslot-deleted` This event announces the deletion of a `lessonSlot` 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","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent preliminaryMeeting-created **Event topic**: `tutorhub-coursescheduling-service-dbevent-preliminarymeeting-created` This event is triggered upon the creation of a `preliminaryMeeting` 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","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent preliminaryMeeting-updated **Event topic**: `tutorhub-coursescheduling-service-dbevent-preliminarymeeting-updated` Activation of this event follows the update of a `preliminaryMeeting` data object. The payload contains the updated information under the `preliminaryMeeting` attribute, along with the original data prior to update, labeled as `old_preliminaryMeeting` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_preliminaryMeeting:{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, preliminaryMeeting:{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent preliminaryMeeting-deleted **Event topic**: `tutorhub-coursescheduling-service-dbevent-preliminarymeeting-deleted` This event announces the deletion of a `preliminaryMeeting` 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","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` # ElasticSearch Index Events Within the `CourseScheduling` 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 availability-created **Event topic**: `elastic-index-tutorhub_availability-created` **Event payload**: ```json {"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event availability-updated **Event topic**: `elastic-index-tutorhub_availability-created` **Event payload**: ```json {"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event availability-deleted **Event topic**: `elastic-index-tutorhub_availability-deleted` **Event payload**: ```json {"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event availability-extended **Event topic**: `elastic-index-tutorhub_availability-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 availability-created **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** 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":"availability","method":"POST","action":"create","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-updated **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-deleted **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-retrived **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"GET","action":"get","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availabilities-listed **Event topic** : `tutorhub-coursescheduling-service-availabilities-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 `availabilities` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availabilities`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availabilities","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","availabilities":[{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_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 lessonslot-created **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** 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":"lessonSlot","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-updated **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-deleted **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-retrived **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"GET","action":"get","appVersion":"Version","rowCount":1,"lessonSlot":{"isActive":true}} ``` ## Route Event lessonslots-listed **Event topic** : `tutorhub-coursescheduling-service-lessonslots-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 `lessonSlots` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlots`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlots","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lessonSlots":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event preliminarymeeting-created **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** 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":"preliminaryMeeting","method":"POST","action":"create","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"coursePack":{},"tutorProfile":{},"tutorUser":{},"student":{}} ``` ## Route Event preliminarymeeting-updated **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeeting","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"student":{},"coursePack":{}} ``` ## Route Event preliminarymeeting-retrived **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeeting","method":"GET","action":"get","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event preliminarymeetings-listed **Event topic** : `tutorhub-coursescheduling-service-preliminarymeetings-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 `preliminaryMeetings` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeetings`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeetings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","preliminaryMeetings":[{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event lessonslot-created **Event topic**: `elastic-index-tutorhub_lessonslot-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event lessonslot-updated **Event topic**: `elastic-index-tutorhub_lessonslot-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event lessonslot-deleted **Event topic**: `elastic-index-tutorhub_lessonslot-deleted` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event lessonslot-extended **Event topic**: `elastic-index-tutorhub_lessonslot-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 availability-created **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** 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":"availability","method":"POST","action":"create","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-updated **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-deleted **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-retrived **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"GET","action":"get","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availabilities-listed **Event topic** : `tutorhub-coursescheduling-service-availabilities-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 `availabilities` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availabilities`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availabilities","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","availabilities":[{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_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 lessonslot-created **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** 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":"lessonSlot","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-updated **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-deleted **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-retrived **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"GET","action":"get","appVersion":"Version","rowCount":1,"lessonSlot":{"isActive":true}} ``` ## Route Event lessonslots-listed **Event topic** : `tutorhub-coursescheduling-service-lessonslots-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 `lessonSlots` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlots`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlots","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lessonSlots":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event preliminarymeeting-created **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** 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":"preliminaryMeeting","method":"POST","action":"create","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"coursePack":{},"tutorProfile":{},"tutorUser":{},"student":{}} ``` ## Route Event preliminarymeeting-updated **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeeting","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"student":{},"coursePack":{}} ``` ## Route Event preliminarymeeting-retrived **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeeting","method":"GET","action":"get","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event preliminarymeetings-listed **Event topic** : `tutorhub-coursescheduling-service-preliminarymeetings-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 `preliminaryMeetings` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeetings`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeetings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","preliminaryMeetings":[{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event preliminarymeeting-created **Event topic**: `elastic-index-tutorhub_preliminarymeeting-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event preliminarymeeting-updated **Event topic**: `elastic-index-tutorhub_preliminarymeeting-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event preliminarymeeting-deleted **Event topic**: `elastic-index-tutorhub_preliminarymeeting-deleted` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event preliminarymeeting-extended **Event topic**: `elastic-index-tutorhub_preliminarymeeting-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 availability-created **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** 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":"availability","method":"POST","action":"create","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-updated **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-deleted **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availability-retrived **Event topic** : `tutorhub-coursescheduling-service-availability-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 `availability` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availability`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availability","method":"GET","action":"get","appVersion":"Version","rowCount":1,"availability":{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event availabilities-listed **Event topic** : `tutorhub-coursescheduling-service-availabilities-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 `availabilities` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`availabilities`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"availabilities","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","availabilities":[{"id":"ID","tutorProfileId":"ID","dayOfWeek":"Enum","dayOfWeek_idx":"Integer","startTime":"String","endTime":"String","isRecurring":"Boolean","specificDate":"Date","teachingMode":"Enum","teachingMode_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 lessonslot-created **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** 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":"lessonSlot","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-updated **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-deleted **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lessonSlot":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDate":"Date","scheduledTime":"String","status":"Enum","status_idx":"Integer","locationType":"Enum","locationType_idx":"Integer","locationDetails":"String","sessionMode":"Enum","sessionMode_idx":"Integer","meetLink":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event lessonslot-retrived **Event topic** : `tutorhub-coursescheduling-service-lessonslot-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 `lessonSlot` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlot`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlot","method":"GET","action":"get","appVersion":"Version","rowCount":1,"lessonSlot":{"isActive":true}} ``` ## Route Event lessonslots-listed **Event topic** : `tutorhub-coursescheduling-service-lessonslots-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 `lessonSlots` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`lessonSlots`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"lessonSlots","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lessonSlots":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event preliminarymeeting-created **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** 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":"preliminaryMeeting","method":"POST","action":"create","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"coursePack":{},"tutorProfile":{},"tutorUser":{},"student":{}} ``` ## Route Event preliminarymeeting-updated **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeeting","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"student":{},"coursePack":{}} ``` ## Route Event preliminarymeeting-retrived **Event topic** : `tutorhub-coursescheduling-service-preliminarymeeting-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 `preliminaryMeeting` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeeting`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeeting","method":"GET","action":"get","appVersion":"Version","rowCount":1,"preliminaryMeeting":{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event preliminarymeetings-listed **Event topic** : `tutorhub-coursescheduling-service-preliminarymeetings-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 `preliminaryMeetings` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`preliminaryMeetings`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"preliminaryMeetings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","preliminaryMeetings":[{"id":"ID","coursePackId":"ID","studentId":"ID","scheduledDatetime":"Date","tutorDecision":"Enum","tutorDecision_idx":"Integer","comments":"String","meetingLink":"String","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 availability # Service Design Specification - Object Design for availability **tutorhub-coursescheduling-service** documentation ## Document Overview This document outlines the object design for the `availability` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## availability Data Object ### Object Overview **Description:** Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. 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 - **uniqueTutorDayAvailability**: [tutorProfileId, dayOfWeek, startTime, endTime] 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 | |----------|------|----------|-------------| | `tutorProfileId` | ID | Yes | FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. | | `dayOfWeek` | Enum | Yes | Day of week: sunday-saturday. | | `startTime` | String | Yes | Start time of window (HH:mm, 24h). | | `endTime` | String | Yes | End time of window (HH:mm, 24h). | | `isRecurring` | Boolean | Yes | If true, this slot recurs weekly. | | `specificDate` | Date | No | Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. | | `teachingMode` | 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. - **tutorProfileId**: '00000000-0000-0000-0000-000000000000' - **dayOfWeek**: monday - **startTime**: 'default' - **endTime**: 'default' - **isRecurring**: true - **teachingMode**: "online" ### Constant Properties `tutorProfileId` 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 `tutorProfileId` `dayOfWeek` `startTime` `endTime` `isRecurring` `specificDate` `teachingMode` 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. - **dayOfWeek**: [sunday, monday, tuesday, wednesday, thursday, friday, saturday] - **teachingMode**: [online, faceToFace, both] ### Elastic Search Indexing `tutorProfileId` `dayOfWeek` `startTime` `endTime` `isRecurring` `specificDate` `teachingMode` 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 `tutorProfileId` `specificDate` 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 `tutorProfileId` 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. - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Filter Properties `teachingMode` 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. - **teachingMode**: Enum has a filter named `teachingMode` --- ### Service Design Specification - Object Design for lessonSlot # Service Design Specification - Object Design for lessonSlot **tutorhub-coursescheduling-service** documentation ## Document Overview This document outlines the object design for the `lessonSlot` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## lessonSlot 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. ### Composite Indexes - **uniqueCoursePackSlot**: [coursePackId, scheduledDate, scheduledTime] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. | | `studentId` | ID | No | FK to auth:user (student). Set on booking. Nullable when open (free). | | `scheduledDate` | Date | Yes | Date for the lesson slot (yyyy-mm-dd). | | `scheduledTime` | String | Yes | Start time of lesson (HH:mm 24h). | | `status` | Enum | Yes | State of lesson slot (free, booked, completed, canceled). | | `locationType` | Enum | No | - | | `locationDetails` | String | No | Optional: Location address/details; editable after booking by either party. | | `sessionMode` | Enum | Yes | Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. | | `meetLink` | String | No | Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. | * 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. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **scheduledDate**: new Date() - **scheduledTime**: 'default' - **status**: free - **locationType**: online - **sessionMode**: "online" ### Constant Properties `coursePackId` `scheduledDate` `scheduledTime` 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 `coursePackId` `studentId` `scheduledDate` `scheduledTime` `status` `locationType` `locationDetails` `sessionMode` `meetLink` 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**: [free, booked, completed, canceled] - **locationType**: [online, studentHome, tutorHome, other] - **sessionMode**: [online, faceToFace] ### Elastic Search Indexing `coursePackId` `studentId` `scheduledDate` `scheduledTime` `status` `locationType` `sessionMode` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `coursePackId` `studentId` `scheduledDate` `scheduledTime` `status` `sessionMode` 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 `coursePackId` `studentId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: No ### Filter Properties `coursePackId` `studentId` `status` `sessionMode` 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. - **coursePackId**: ID has a filter named `coursePackId` - **studentId**: ID has a filter named `studentId` - **status**: Enum has a filter named `status` - **sessionMode**: Enum has a filter named `sessionMode` --- ### Service Design Specification - Object Design for preliminaryMeeting # Service Design Specification - Object Design for preliminaryMeeting **tutorhub-coursescheduling-service** documentation ## Document Overview This document outlines the object design for the `preliminaryMeeting` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## preliminaryMeeting Data Object ### Object Overview **Description:** Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. 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 - **uniqueCoursePackStudentMeeting**: [coursePackId, studentId] 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 | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to tutorCatalog:coursePack (the advanced course) | | `studentId` | ID | Yes | FK to auth:user (student who requested). | | `scheduledDatetime` | Date | No | Datetime for screening meeting; may be null until both parties agree. | | `tutorDecision` | Enum | Yes | - | | `comments` | String | No | Optional field for tutor to provide comments/notes about screening result. | | `meetingLink` | String | No | Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. | * 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. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **studentId**: '00000000-0000-0000-0000-000000000000' - **tutorDecision**: "pending" ### Constant Properties `coursePackId` `studentId` 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 `coursePackId` `studentId` `scheduledDatetime` `tutorDecision` `comments` `meetingLink` 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. - **tutorDecision**: [pending, approved, rejected] ### Elastic Search Indexing `coursePackId` `studentId` `scheduledDatetime` `tutorDecision` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `coursePackId` `studentId` `tutorDecision` 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 `coursePackId` `studentId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes --- ## Business APIs ### Business API Design Specification - `Create Availability` # Business API Design Specification - `Create Availability` 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 `createAvailability` 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 `createAvailability` Business API is designed to handle a `create` operation on the `Availability` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor creates available time window for teaching. Only owner tutor or admin. ## 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 `availability-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 `createAvailability` Business API includes a REST controller that can be triggered via the following route: `/v1/availabilities` 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 `createAvailability` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAvailability` 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. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `availabilityId` | `ID` | `No` | `-` | `body` | `availabilityId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `tutorProfileId` | `ID` | `Yes` | `-` | `body` | `tutorProfileId` | | **Description:** | FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. | | | | | | | | | | | | | `dayOfWeek` | `Enum` | `Yes` | `-` | `body` | `dayOfWeek` | | **Description:** | Day of week: sunday-saturday. | | | | | | | | | | | | | `startTime` | `String` | `Yes` | `-` | `body` | `startTime` | | **Description:** | Start time of window (HH:mm, 24h). | | | | | | | | | | | | | `endTime` | `String` | `Yes` | `-` | `body` | `endTime` | | **Description:** | End time of window (HH:mm, 24h). | | | | | | | | | | | | | `isRecurring` | `Boolean` | `Yes` | `-` | `body` | `isRecurring` | | **Description:** | If true, this slot recurs weekly. | | | | | | | | | | | | | `specificDate` | `Date` | `No` | `-` | `body` | `specificDate` | | **Description:** | Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. | | | | | | | | | | | | | `teachingMode` | `Enum` | `Yes` | `-` | `body` | `teachingMode` | | **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 `createAvailability` 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: `[tutor, 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.availabilityId, tutorProfileId: this.tutorProfileId, dayOfWeek: this.dayOfWeek, startTime: this.startTime, endTime: this.endTime, isRecurring: this.isRecurring, specificDate: this.specificDate, teachingMode: this.teachingMode, 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 `createAvailability` api has got 7 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | dayOfWeek | Enum | true | request.body?.["dayOfWeek"] | | startTime | String | true | request.body?.["startTime"] | | endTime | String | true | request.body?.["endTime"] | | isRecurring | Boolean | true | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | true | request.body?.["teachingMode"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/availabilities** ```js axios({ method: 'POST', url: '/v1/availabilities', data: { tutorProfileId:"ID", dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"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 **`availability`** 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": "availability", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Availability` # Business API Design Specification - `Update Availability` 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 `updateAvailability` 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 `updateAvailability` Business API is designed to handle a `update` operation on the `Availability` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor updates an availability record (only own, or admin). ## 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 `availability-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 `updateAvailability` Business API includes a REST controller that can be triggered via the following route: `/v1/availabilities/:availabilityId` 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 `updateAvailability` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateAvailability` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `availabilityId` | `ID` | `Yes` | `-` | `urlpath` | `availabilityId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `dayOfWeek` | `Enum` | `No` | `-` | `body` | `dayOfWeek` | | **Description:** | Day of week: sunday-saturday. | | | | | | | | | | | | | `startTime` | `String` | `No` | `-` | `body` | `startTime` | | **Description:** | Start time of window (HH:mm, 24h). | | | | | | | | | | | | | `endTime` | `String` | `No` | `-` | `body` | `endTime` | | **Description:** | End time of window (HH:mm, 24h). | | | | | | | | | | | | | `isRecurring` | `Boolean` | `No` | `-` | `body` | `isRecurring` | | **Description:** | If true, this slot recurs weekly. | | | | | | | | | | | | | `specificDate` | `Date` | `No` | `-` | `body` | `specificDate` | | **Description:** | Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. | | | | | | | | | | | | | `teachingMode` | `Enum` | `No` | `-` | `body` | `teachingMode` | | **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 `updateAvailability` 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: `[tutor, 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.availabilityId},{isActive:true}]}), {"path":"services[2].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 { dayOfWeek: this.dayOfWeek, startTime: this.startTime, endTime: this.endTime, isRecurring: this.isRecurring, specificDate: this.specificDate, teachingMode: this.teachingMode, } ``` ## 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 `updateAvailability` api has got 7 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | | dayOfWeek | Enum | false | request.body?.["dayOfWeek"] | | startTime | String | false | request.body?.["startTime"] | | endTime | String | false | request.body?.["endTime"] | | isRecurring | Boolean | false | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | false | request.body?.["teachingMode"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/availabilities/:availabilityId** ```js axios({ method: 'PATCH', url: `/v1/availabilities/${availabilityId}`, data: { dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"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 **`availability`** 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": "availability", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Availability` # Business API Design Specification - `Delete Availability` 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 `deleteAvailability` 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 `deleteAvailability` Business API is designed to handle a `delete` operation on the `Availability` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor deletes an availability record (only own, or admin). ## 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 `availability-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 `deleteAvailability` Business API includes a REST controller that can be triggered via the following route: `/v1/availabilities/:availabilityId` 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 `deleteAvailability` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteAvailability` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `availabilityId` | `ID` | `Yes` | `-` | `urlpath` | `availabilityId` | | **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 `deleteAvailability` 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: `[tutor, 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.availabilityId},{isActive:true}]}), {"path":"services[2].businessLogic[2].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 `deleteAvailability` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/availabilities/:availabilityId** ```js axios({ method: 'DELETE', url: `/v1/availabilities/${availabilityId}`, 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 **`availability`** 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": "availability", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Availability` # Business API Design Specification - `Get Availability` 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 `getAvailability` 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 `getAvailability` Business API is designed to handle a `get` operation on the `Availability` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get one availability by id (tutor/owner or 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 `availability-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 `getAvailability` Business API includes a REST controller that can be triggered via the following route: `/v1/availabilities/:availabilityId` 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 `getAvailability` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAvailability` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `availabilityId` | `ID` | `Yes` | `-` | `urlpath` | `availabilityId` | | **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 `getAvailability` 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: `[tutor, 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.availabilityId},{isActive:true}]}), {"path":"services[2].businessLogic[3].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 `getAvailability` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/availabilities/:availabilityId** ```js axios({ method: 'GET', url: `/v1/availabilities/${availabilityId}`, 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 **`availability`** 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": "availability", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Availabilities` # Business API Design Specification - `List Availabilities` 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 `listAvailabilities` 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 `listAvailabilities` Business API is designed to handle a `list` operation on the `Availability` 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 `availabilities-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 `listAvailabilities` Business API includes a REST controller that can be triggered via the following route: `/v1/listavailabilities/:tutorProfileId` 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 `listAvailabilities` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAvailabilities` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `Yes` | `-` | `urlpath` | `tutorProfileId` | | **Description:** | FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit.. The parameter is used to query data. | | | | | | | | | | | | ### Filter Parameters The `listAvailabilities` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `teachingMode` Filter **Type:** `Enum` **Description:** Filter by teachingMode **Location:** Query Parameter **Usage:** - Single value: `?teachingMode=` (case-insensitive) - Multiple values: `?teachingMode=&teachingMode=` - Null check: `?teachingMode=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/listavailabilities/:tutorProfileId?teachingMode=active // Get records with multiple enum values (use multiple parameters) GET /v1/listavailabilities/:tutorProfileId?teachingMode=active&teachingMode=pending // Get records without this field GET /v1/listavailabilities/:tutorProfileId?teachingMode=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 `listAvailabilities` 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: `[user, student, tutor, 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 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:[{tutorProfileId:{"$eq":this.tutorProfileId}},{isActive:true}]}), {"path":"services[2].businessLogic[4].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 `listAvailabilities` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | The `listAvailabilities` 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | teachingMode | Enum | No | Filter by teachingMode | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/listavailabilities/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/listavailabilities/${tutorProfileId}`, data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // teachingMode: '' // Filter by teachingMode } }); ``` ### 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 **`availabilities`** 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": "availabilities", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "availabilities": [ { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_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 - `Create Lessonslot` # Business API Design Specification - `Create Lessonslot` 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 `createLessonSlot` 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 `createLessonSlot` Business API is designed to handle a `create` operation on the `LessonSlot` 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 `lessonslot-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 `createLessonSlot` Business API includes a REST controller that can be triggered via the following route: `/v1/lessonslots` 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 `createLessonSlot` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createLessonSlot` Business API has 10 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `lessonSlotId` | `ID` | `No` | `-` | `body` | `lessonSlotId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `body` | `coursePackId` | | **Description:** | FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. | | | | | | | | | | | | | `studentId` | `ID` | `No` | `-` | `body` | `studentId` | | **Description:** | FK to auth:user (student). Set on booking. Nullable when open (free). | | | | | | | | | | | | | `scheduledDate` | `Date` | `Yes` | `-` | `body` | `scheduledDate` | | **Description:** | Date for the lesson slot (yyyy-mm-dd). | | | | | | | | | | | | | `scheduledTime` | `String` | `Yes` | `-` | `body` | `scheduledTime` | | **Description:** | Start time of lesson (HH:mm 24h). | | | | | | | | | | | | | `status` | `Enum` | `Yes` | `-` | `body` | `status` | | **Description:** | State of lesson slot (free, booked, completed, canceled). | | | | | | | | | | | | | `locationType` | `Enum` | `No` | `-` | `body` | `locationType` | | **Description:** | - | | | | | | | | | | | | | `locationDetails` | `String` | `No` | `-` | `body` | `locationDetails` | | **Description:** | Optional: Location address/details; editable after booking by either party. | | | | | | | | | | | | | `sessionMode` | `Enum` | `Yes` | `-` | `body` | `sessionMode` | | **Description:** | Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. | | | | | | | | | | | | | `meetLink` | `String` | `No` | `-` | `body` | `meetLink` | | **Description:** | Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. | | | | | | | | | | | | ### 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 `createLessonSlot` 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: `[tutor, admin, student, user, 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.lessonSlotId, coursePackId: this.coursePackId, studentId: this.studentId, scheduledDate: this.scheduledDate, scheduledTime: this.scheduledTime, status: this.status, locationType: this.locationType, locationDetails: this.locationDetails, sessionMode: this.sessionMode, meetLink: this.meetLink, 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 : fetchCoursePackFromCatalog **Action Type**: `FetchObjectAction` Fetch course pack from tutorCatalog to get tutorProfileId for availability lookup ```js class Api { async fetchCoursePackFromCatalog() { // Fetch Object on childObject coursePack const userQuery = { $and: [ { id: runMScript(() => this.coursePackId, { path: "services[2].businessLogic[5].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("coursePack"); const data = await elasticIndex.getOne(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:coursePack"); } return data ? { id: data["id"], tutorProfileId: data["tutorProfileId"], title: data["title"], isPublished: data["isPublished"], } : null; } } ``` --- ### [6] Action : fetchTutorAvailabilities **Action Type**: `FetchObjectAction` Fetch tutor availability windows for this course's tutor ```js class Api { async fetchTutorAvailabilities() { // Fetch Object on childObject availability const userQuery = { $and: [ runMScript( () => ({ tutorProfileId: this.slotCoursePack.tutorProfileId }), { path: "services[2].businessLogic[5].actions.fetchObjectActions[1].whereClause", }, ), { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object list from db const dataList = (await getAvailabilityListByQuery(scriptQuery)) ?? []; return dataList; } } ``` --- ### [7] Action : runSlotAvailabilityCheck **Action Type**: `FunctionCallAction` Validate slot date/time against tutor availability ```js class Api { async runSlotAvailabilityCheck() { try { return runMScript( () => LIB.validateSlotAgainstAvailability( this.tutorAvailabilities, this.scheduledDate, this.scheduledTime, ), { path: "services[2].businessLogic[5].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error( "Error in FunctionCallAction runSlotAvailabilityCheck:", err, ); throw err; } } } ``` --- ### [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] Action : enforceSlotAvailability **Action Type**: `ValidationAction` Block slot creation if it does not match any tutor availability window ```js class Api { async enforceSlotAvailability() { const isValid = runMScript( () => this.slotValidation && this.slotValidation.valid === true, { path: "services[2].businessLogic[5].actions.validationActions[1].validationScript", }, ); if (!isValid) { throw new BadRequestError( "No matching tutor availability for the requested day/time. Please check the tutor's available schedule.", ); } return isValid; } } ``` --- ### [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 `createLessonSlot` api has got 9 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | false | request.body?.["studentId"] | | scheduledDate | Date | true | request.body?.["scheduledDate"] | | scheduledTime | String | true | request.body?.["scheduledTime"] | | status | Enum | true | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | true | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/lessonslots** ```js axios({ method: 'POST', url: '/v1/lessonslots', data: { coursePackId:"ID", studentId:"ID", scheduledDate:"Date", scheduledTime:"String", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"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 **`lessonSlot`** 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": "lessonSlot", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Lessonslot` # Business API Design Specification - `Update Lessonslot` 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 `updateLessonSlot` 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 `updateLessonSlot` Business API is designed to handle a `update` operation on the `LessonSlot` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Update lesson slot status/location. Tutor can edit any of their coursePack's slots; student can update their own booked slot location (if booked). Admin has override right. ## 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 `lessonslot-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 `updateLessonSlot` Business API includes a REST controller that can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` 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 `updateLessonSlot` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateLessonSlot` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `lessonSlotId` | `ID` | `Yes` | `-` | `urlpath` | `lessonSlotId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `studentId` | `ID` | `No` | `-` | `body` | `studentId` | | **Description:** | FK to auth:user (student). Set on booking. Nullable when open (free). | | | | | | | | | | | | | `status` | `Enum` | `No` | `-` | `body` | `status` | | **Description:** | State of lesson slot (free, booked, completed, canceled). | | | | | | | | | | | | | `locationType` | `Enum` | `No` | `-` | `body` | `locationType` | | **Description:** | - | | | | | | | | | | | | | `locationDetails` | `String` | `No` | `-` | `body` | `locationDetails` | | **Description:** | Optional: Location address/details; editable after booking by either party. | | | | | | | | | | | | | `sessionMode` | `Enum` | `No` | `-` | `body` | `sessionMode` | | **Description:** | Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. | | | | | | | | | | | | | `meetLink` | `String` | `No` | `-` | `body` | `meetLink` | | **Description:** | Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. | | | | | | | | | | | | ### 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 `updateLessonSlot` 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: `[user, student, tutor, 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.lessonSlotId},{isActive:true}]}), {"path":"services[2].businessLogic[6].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 { studentId: this.studentId, status: this.status, locationType: this.locationType, locationDetails: this.locationDetails, sessionMode: this.sessionMode, meetLink: this.meetLink, } ``` ## 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 `updateLessonSlot` api has got 7 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | | studentId | ID | false | request.body?.["studentId"] | | status | Enum | false | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | false | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'PATCH', url: `/v1/lessonslots/${lessonSlotId}`, data: { studentId:"ID", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"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 **`lessonSlot`** 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": "lessonSlot", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Lessonslot` # Business API Design Specification - `Delete Lessonslot` 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 `deleteLessonSlot` 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 `deleteLessonSlot` Business API is designed to handle a `delete` operation on the `LessonSlot` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor can remove their own slot if free/booked. Admin can remove any. (Student may not delete). ## 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 `lessonslot-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 `deleteLessonSlot` Business API includes a REST controller that can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` 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 `deleteLessonSlot` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteLessonSlot` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `lessonSlotId` | `ID` | `Yes` | `-` | `urlpath` | `lessonSlotId` | | **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 `deleteLessonSlot` 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: `[tutor, 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.lessonSlotId},{isActive:true}]}), {"path":"services[2].businessLogic[7].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 `deleteLessonSlot` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'DELETE', url: `/v1/lessonslots/${lessonSlotId}`, 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 **`lessonSlot`** 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": "lessonSlot", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Lessonslot` # Business API Design Specification - `Get Lessonslot` 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 `getLessonSlot` 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 `getLessonSlot` Business API is designed to handle a `get` operation on the `LessonSlot` 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 `lessonslot-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 `getLessonSlot` Business API includes a REST controller that can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` 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 `getLessonSlot` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getLessonSlot` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `lessonSlotId` | `ID` | `Yes` | `-` | `urlpath` | `lessonSlotId` | | **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 `getLessonSlot` 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: `[user, student, tutor, 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.", `id`,`coursePackId`,`studentId`,`scheduledDate`,`scheduledTime`,`status`,`locationType`,`locationDetails`,`sessionMode`,`meetLink` ## 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.lessonSlotId},{isActive:true}]}), {"path":"services[2].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 `getLessonSlot` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'GET', url: `/v1/lessonslots/${lessonSlotId}`, 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 **`lessonSlot`** 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": "lessonSlot", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "isActive": true } } ``` --- ### Business API Design Specification - `List Lessonslots` # Business API Design Specification - `List Lessonslots` 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 `listLessonSlots` 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 `listLessonSlots` Business API is designed to handle a `list` operation on the `LessonSlot` 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 `lessonslots-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 `listLessonSlots` Business API includes a REST controller that can be triggered via the following route: `/v1/lessonslots` 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 `listLessonSlots` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listLessonSlots` 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 `listLessonSlots` 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: `[user, student, tutor, 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.", `id`,`coursePackId`,`studentId`,`scheduledDate`,`scheduledTime`,`status`,`locationType`,`locationDetails`,`sessionMode`,`meetLink` ## 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 {isActive: true} ``` **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. ```js // Addtional Clause Name : filterByStudentId // condition doWhen // this.queryData.studentId // condition excludeWhen // No excludeWhen condtion defined // clause object { studentId: this.queryData.studentId } ``` ```js // Addtional Clause Name : filterByCoursePackId // condition doWhen // this.queryData.coursePackId // condition excludeWhen // No excludeWhen condtion defined // clause object { coursePackId: this.queryData.coursePackId } ``` **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{isActive: true},{isActive:true}]}), {"path":"services[2].businessLogic[9].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 `listLessonSlots` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/lessonslots** ```js axios({ method: 'GET', url: '/v1/lessonslots', 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 **`lessonSlots`** 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": "lessonSlots", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "lessonSlots": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Preliminarymeeting` # Business API Design Specification - `Create Preliminarymeeting` 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 `createPreliminaryMeeting` 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 `createPreliminaryMeeting` Business API is designed to handle a `create` operation on the `PreliminaryMeeting` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Student requests a screening meeting; only created if related coursePack requires screening. ## 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 `preliminarymeeting-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 `createPreliminaryMeeting` Business API includes a REST controller that can be triggered via the following route: `/v1/preliminarymeetings` 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 `createPreliminaryMeeting` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createPreliminaryMeeting` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `preliminaryMeetingId` | `ID` | `No` | `-` | `body` | `preliminaryMeetingId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `body` | `coursePackId` | | **Description:** | FK to tutorCatalog:coursePack (the advanced course) | | | | | | | | | | | | | `studentId` | `ID` | `Yes` | `-` | `body` | `studentId` | | **Description:** | FK to auth:user (student who requested). | | | | | | | | | | | | | `scheduledDatetime` | `Date` | `No` | `-` | `body` | `scheduledDatetime` | | **Description:** | Datetime for screening meeting; may be null until both parties agree. | | | | | | | | | | | | | `tutorDecision` | `Enum` | `Yes` | `-` | `body` | `tutorDecision` | | **Description:** | - | | | | | | | | | | | | | `comments` | `String` | `No` | `-` | `body` | `comments` | | **Description:** | Optional field for tutor to provide comments/notes about screening result. | | | | | | | | | | | | | `meetingLink` | `String` | `No` | `-` | `body` | `meetingLink` | | **Description:** | Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. | | | | | | | | | | | | ### 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 `createPreliminaryMeeting` 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: `[user, student, 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.preliminaryMeetingId, coursePackId: this.coursePackId, studentId: this.studentId, scheduledDatetime: this.scheduledDatetime, tutorDecision: this.tutorDecision, comments: this.comments, meetingLink: this.meetingLink, 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] Action : fetchCoursePack **Action Type**: `FetchObjectAction` Fetch course pack for notification ```js class Api { async fetchCoursePack() { // Fetch Object on childObject coursePack const userQuery = { $and: [ { id: runMScript(() => this.coursePackId, { path: "services[2].businessLogic[10].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("coursePack"); const data = await elasticIndex.getOne(scriptQuery); return data ? { title: data["title"], tutorProfileId: data["tutorProfileId"], } : null; } } ``` --- ### [9] Action : fetchTutorProfile **Action Type**: `FetchObjectAction` Fetch tutor profile to get tutorId ```js class Api { async fetchTutorProfile() { // Fetch Object on childObject tutorProfile const userQuery = { $and: [ { id: runMScript(() => this.coursePack.tutorProfileId, { path: "services[2].businessLogic[10].actions.fetchObjectActions[1].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("tutorProfile"); const data = await elasticIndex.getOne(scriptQuery); return data ? { tutorId: data["tutorId"], } : null; } } ``` --- ### [10] Action : fetchTutorUser **Action Type**: `FetchObjectAction` Fetch tutor user for email notification ```js class Api { async fetchTutorUser() { // Fetch Object on childObject user const userQuery = { $and: [ { id: runMScript(() => this.tutorProfile.tutorId, { path: "services[2].businessLogic[10].actions.fetchObjectActions[2].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("user"); const data = await elasticIndex.getOne(scriptQuery); return data ? { fullname: data["fullname"], email: data["email"], } : null; } } ``` --- ### [11] Action : fetchStudent **Action Type**: `FetchObjectAction` Fetch student name for email ```js class Api { async fetchStudent() { // Fetch Object on childObject user const userQuery = { $and: [ { id: runMScript(() => this.studentId, { path: "services[2].businessLogic[10].actions.fetchObjectActions[3].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("user"); const data = await elasticIndex.getOne(scriptQuery); return data ? { fullname: data["fullname"], } : null; } } ``` --- ### [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 `createPreliminaryMeeting` api has got 6 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | true | request.body?.["studentId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | true | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/preliminarymeetings** ```js axios({ method: 'POST', url: '/v1/preliminarymeetings', data: { coursePackId:"ID", studentId:"ID", scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"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 **`preliminaryMeeting`** 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": "preliminaryMeeting", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "coursePack": { "tutorProfileId": "ID", "title": "String" }, "tutorProfile": { "tutorId": "ID" }, "tutorUser": { "email": "String", "fullname": "String" }, "student": { "fullname": "String" } } ``` --- ### Business API Design Specification - `Update Preliminarymeeting` # Business API Design Specification - `Update Preliminarymeeting` 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 `updatePreliminaryMeeting` 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 `updatePreliminaryMeeting` Business API is designed to handle a `update` operation on the `PreliminaryMeeting` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor updates scheduled date/time, decision, or comments for screening meeting. Only tutor of coursePack or admin can approve/reject/set date; student can only propose initial. ## 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 `preliminarymeeting-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 `updatePreliminaryMeeting` Business API includes a REST controller that can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` 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 `updatePreliminaryMeeting` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updatePreliminaryMeeting` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `preliminaryMeetingId` | `ID` | `Yes` | `-` | `urlpath` | `preliminaryMeetingId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `scheduledDatetime` | `Date` | `No` | `-` | `body` | `scheduledDatetime` | | **Description:** | Datetime for screening meeting; may be null until both parties agree. | | | | | | | | | | | | | `tutorDecision` | `Enum` | `No` | `-` | `body` | `tutorDecision` | | **Description:** | - | | | | | | | | | | | | | `comments` | `String` | `No` | `-` | `body` | `comments` | | **Description:** | Optional field for tutor to provide comments/notes about screening result. | | | | | | | | | | | | | `meetingLink` | `String` | `No` | `-` | `body` | `meetingLink` | | **Description:** | Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. | | | | | | | | | | | | ### 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 `updatePreliminaryMeeting` 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: `[tutor, 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.preliminaryMeetingId},{isActive:true}]}), {"path":"services[2].businessLogic[11].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 { scheduledDatetime: this.scheduledDatetime, tutorDecision: this.tutorDecision, comments: this.comments, meetingLink: this.meetingLink, } ``` ## 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] Action : fetchStudent **Action Type**: `FetchObjectAction` Fetch student for screening decision email ```js class Api { async fetchStudent() { // Fetch Object on childObject user const userQuery = { $and: [ { id: runMScript(() => this.data.studentId, { path: "services[2].businessLogic[11].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("user"); const data = await elasticIndex.getOne(scriptQuery); return data ? { fullname: data["fullname"], email: data["email"], } : null; } } ``` --- ### [12] Action : fetchCoursePack **Action Type**: `FetchObjectAction` Fetch course pack title for email ```js class Api { async fetchCoursePack() { // Fetch Object on childObject coursePack const userQuery = { $and: [ { id: runMScript(() => this.data.coursePackId, { path: "services[2].businessLogic[11].actions.fetchObjectActions[1].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("coursePack"); const data = await elasticIndex.getOne(scriptQuery); return data ? { title: data["title"], } : null; } } ``` --- ### [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 `updatePreliminaryMeeting` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | false | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'PATCH', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"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 **`preliminaryMeeting`** 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": "preliminaryMeeting", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "student": { "email": "String", "fullname": "String" }, "coursePack": { "title": "String" } } ``` --- ### Business API Design Specification - `Get Preliminarymeeting` # Business API Design Specification - `Get Preliminarymeeting` 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 `getPreliminaryMeeting` 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 `getPreliminaryMeeting` Business API is designed to handle a `get` operation on the `PreliminaryMeeting` 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 single meeting by id: only tutor, student, or admin can access. ## 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 `preliminarymeeting-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 `getPreliminaryMeeting` Business API includes a REST controller that can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` 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 `getPreliminaryMeeting` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getPreliminaryMeeting` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `preliminaryMeetingId` | `ID` | `Yes` | `-` | `urlpath` | `preliminaryMeetingId` | | **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 `getPreliminaryMeeting` 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: `[user, student, tutor, 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.preliminaryMeetingId},{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 `getPreliminaryMeeting` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'GET', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, 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 **`preliminaryMeeting`** 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": "preliminaryMeeting", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `List Preliminarymeetings` # Business API Design Specification - `List Preliminarymeetings` 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 `listPreliminaryMeetings` 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 `listPreliminaryMeetings` Business API is designed to handle a `list` operation on the `PreliminaryMeeting` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Tutor can list all meetings for their courses; students see their own; admin sees 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** : `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 `preliminarymeetings-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 `listPreliminaryMeetings` Business API includes a REST controller that can be triggered via the following route: `/v1/preliminarymeetings` 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 `listPreliminaryMeetings` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listPreliminaryMeetings` 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 `listPreliminaryMeetings` 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: `[user, student, tutor, 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[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 `listPreliminaryMeetings` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/preliminarymeetings** ```js axios({ method: 'GET', url: '/v1/preliminarymeetings', 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 **`preliminaryMeetings`** 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": "preliminaryMeetings", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "preliminaryMeetings": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ## Service Library - `courseScheduling` # Service Library - `courseScheduling` This document provides a complete reference of the custom code library for the `courseScheduling` 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/")`. ### `validateSlotAgainstAvailability.js` ```js module.exports = function validateSlotAgainstAvailability(availabilities, scheduledDate, scheduledTime) { if (!availabilities || availabilities.length === 0) { return { valid: false, error: 'No tutor availability found for this course.' }; } const dateStr = (scheduledDate || '').split('T')[0]; const d = new Date(dateStr + 'T00:00:00Z'); if (isNaN(d.getTime())) return { valid: false, error: 'Invalid scheduled date.' }; const dayNames = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday']; const slotDay = dayNames[d.getUTCDay()]; const slotHour = parseInt((scheduledTime || '').split(':')[0], 10); const slotMin = parseInt((scheduledTime || '').split(':')[1], 10) || 0; const slotMinutes = slotHour * 60 + slotMin; for (const av of availabilities) { if (av.dayOfWeek !== slotDay) continue; if (!av.isRecurring && av.specificDate) { const avDate = (av.specificDate || '').split('T')[0]; if (avDate !== dateStr) continue; } const [sh, sm] = (av.startTime || '').split(':').map(Number); const [eh, em] = (av.endTime || '').split(':').map(Number); const startMin = sh * 60 + (sm || 0); const endMin = eh * 60 + (em || 0); if (slotMinutes >= startMin && slotMinutes < endMin) { return { valid: true, error: null }; } } return { valid: false, error: 'No matching availability for ' + slotDay + ' at ' + scheduledTime + '.' }; }; ``` --- *This document was generated from the service library configuration and should be kept in sync with design changes.* --- # EnrollmentManagement Service ## Service Design Specification # Service Design Specification **tutorhub-enrollmentmanagement-service** documentation **Version:** `1.0.76` ## Scope This document provides a structured architectural overview of the `enrollmentManagement` microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment. The document is intended to serve multiple audiences: * **Service architects** can use it to validate design decisions and ensure alignment with broader architectural goals. * **Developers and maintainers** will find it useful for understanding the structure and behavior of the service, facilitating easier debugging, feature extension, and integration with other systems. * **Stakeholders and reviewers** can use it to gain a clear understanding of the service's capabilities and domain logic. > **Note for Frontend Developers**: While this document is valuable for understanding business logic and data interactions, please refer to the [Service API Documentation](#) for endpoint-level specifications and integration details. > **Note for Backend Developers**: Since the code for this service is automatically generated by Mindbricks, you typically won't need to implement or modify it manually. However, this document is especially valuable when you're building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service's data contracts, business rules, and API structure, helping ensure compatibility and correct integration. ## `EnrollmentManagement` Service Settings Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. ### Service Overview This service is configured to listen for HTTP requests on port `3003`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-enrollmentmanagement-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api` * **Production:** `https://tutorhub.mindbricks.co/enrollmentmanagement-api` ### Authentication & Security - **Login Required**: Yes This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-enrollmentmanagement-service`. Data deletion is managed using a **soft delete** strategy. Instead of removing records from the database, they are flagged as inactive by setting the `isActive` field to `false`. | Object Name | Description | Public Access | |-------------|-------------|---------------| | `enrollment` | Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. | accessPrivate | | `refundRequest` | A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. | accessPrivate | | `sys_enrollmentPayment` | A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object's checkout config | accessPrivate | | `sys_paymentCustomer` | A payment storage object to store the customer values of the payment platform | accessPrivate | | `sys_paymentMethod` | A payment storage object to store the payment methods of the platform customers | accessPrivate | ## enrollment Data Object ### Object Overview **Description:** Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **enrollment_unique_booking**: [studentId, coursePackId] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Stripe Integration This data object is configured to integrate with Stripe for order management of `enrollment`. It is designed to handle payment processing and order tracking. To manage payments, Mindbricks will design additional Business API routes arround this data object, which will be used checkout orders and charge customers. - **Order Name**: `enrollment` - **Order Id Property**: This MScript expression is used to extract the order's unique identifier from the data object. - **Order Amount Property**: This MScript expression is used to determine the order amount for payment. It should return a numeric value representing the total amount to be charged. - **Order Currency Property**: This MScript expression is used to determine the currency for the order. It should return a string representing the currency code (e.g., "USD", "EUR"). - **Order Description Property**: `Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}` This MScript expression is used to provide a description for the order, which will be shown in Stripe and on customer receipts. It should return a string that describes the order. - **Order Status Property**: paymentStatus This property is selected as the order status property, which will be used to track the current status of the order. It will be automatically updated based on payment results from Stripe. - **Order Status Update Date Property**: updatedAt This property is selected to record the timestamp of the last order status update. It will be automatically managed during payment events to reflect when the status was last changed. - **Order Owner Id Property**: studentId This property is selected as the order owner property, which will be used to track the user who owns the order. It will be used to ensure correct access control in payment flows, allowing only the owner to manage their orders. - **Map Payment Result to Order Status**: This configuration defines how Stripe's payment results (e.g., started, success, failed, canceled) map to internal order statuses., `paymentResultStarted` status will be mapped to a local value using `"pending"` and will be set to `paymentStatus`property. `paymentResultCanceled` status will be mapped to a local value using `"pending"` and will be set to `paymentStatus` property. `paymentResultFailed` status will be mapped to a local value using `"pending"` and will be set to `paymentStatus` property. `paymentResultSuccess` status will be mapped to a local value using `"paid"` and will be set to `paymentStatus` property. - **On Checkout Error**: if an error occurs during the checkout process, the API will continue to execute, allowing for custom error handling. In this case, the payment error will ve recorded as a status update. To make a retry a new checkout, a new order will be created with the same data as the original order. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to purchased course pack. | | `studentId` | ID | Yes | FK to enrolling student (auth:user). | | `tutorProfileId` | ID | Yes | FK to the course's tutorProfile for admin/analytics. | | `lessonSlotIds` | ID | Yes | IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). | | `totalAmount` | Double | Yes | Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). | | `currency` | String | Yes | 3-letter ISO currency code (e.g., 'USD', 'EUR'). | | `paymentStatus` | Enum | Yes | Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation). | | `refundStatus` | Enum | Yes | Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. | | `enrollmentStatus` | Enum | Yes | Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated). | | `enrolledAt` | Date | No | Datetime of completed enrollment (post-payment). | | `paymentConfirmation` | Enum | Yes | An automatic property that is used to check the confirmed status of the payment set by webhooks. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `lessonSlotIds` Array properties can hold multiple values and are indicated by the `[]` suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **studentId**: '00000000-0000-0000-0000-000000000000' - **tutorProfileId**: '00000000-0000-0000-0000-000000000000' - **lessonSlotIds**: [] - **totalAmount**: 0.0 - **currency**: USD - **paymentStatus**: pending - **refundStatus**: notRequested - **enrollmentStatus**: pending - **paymentConfirmation**: pending ### Always Create with Default Values Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created. - **paymentStatus**: Will be created with value `pending` - **enrollmentStatus**: Will be created with value `pending` - **paymentConfirmation**: Will be created with value `pending` ### Constant Properties `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` `totalAmount` `currency` `enrolledAt` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `paymentStatus` `refundStatus` `enrollmentStatus` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values. - **paymentStatus**: [pending, paid, refunded] - **refundStatus**: [notRequested, eligible, processed, ineligible] - **enrollmentStatus**: [pending, active, completed, canceled] - **paymentConfirmation**: [pending, processing, paid, canceled] ### Elastic Search Indexing `coursePackId` `studentId` `totalAmount` `currency` `paymentStatus` `refundStatus` `enrollmentStatus` `enrolledAt` `paymentConfirmation` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` `totalAmount` `paymentStatus` `refundStatus` `enrollmentStatus` `paymentConfirmation` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Secondary Key Properties `paymentConfirmation` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Relation Properties `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **lessonSlotIds**: ID Relation to `lessonSlot`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Session Data Properties `studentId` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **studentId**: ID property will be mapped to the session parameter `userId`. This property is also used to store the owner of the session data, allowing for ownership checks and access control. ### Filter Properties `paymentConfirmation` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled. - **paymentConfirmation**: Enum has a filter named `paymentConfirmation` ## refundRequest Data Object ### Object Overview **Description:** A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **unique_enrollment_refund**: [enrollmentId] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `enrollmentId` | ID | Yes | FK to enrollment object for which refund is being requested (unique: one refund per enrollment). | | `requestedBy` | ID | Yes | User (student) making the refund request (auth:user id). | | `requestedAt` | Date | Yes | Datetime refund was requested. | | `processedAt` | Date | No | When refund was processed by system (auto-approval). | | `status` | Enum | Yes | Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). | | `reason` | String | Yes | User-supplied reason for requesting refund. | | `firstLessonCompleted` | Boolean | Yes | True if this refund is after first lesson (enforced by workflow); must be checked before approval. | | `adminNote` | String | No | Admin note explaining the refund decision (approve/reject reason). | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **enrollmentId**: '00000000-0000-0000-0000-000000000000' - **requestedBy**: '00000000-0000-0000-0000-000000000000' - **requestedAt**: new Date() - **status**: pending - **reason**: 'default' - **firstLessonCompleted**: false ### Constant Properties `enrollmentId` `requestedBy` `requestedAt` `reason` `firstLessonCompleted` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `processedAt` `status` `adminNote` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values. - **status**: [pending, approved, rejected, autoApproved] ### Database Indexing `enrollmentId` `requestedBy` `requestedAt` `processedAt` `status` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Unique Properties `enrollmentId` Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option. ### Relation Properties `enrollmentId` `requestedBy` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **enrollmentId**: ID Relation to `enrollment`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **requestedBy**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Session Data Properties `requestedBy` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **requestedBy**: ID property will be mapped to the session parameter `userId`. ## sys_enrollmentPayment Data Object ### Object Overview **Description:** A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object's checkout config This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `ownerId` | ID | No | An ID value to represent owner user who created the order | | `orderId` | ID | Yes | an ID value to represent the orderId which is the ID parameter of the source enrollment object | | `paymentId` | String | Yes | A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type | | `paymentStatus` | String | Yes | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | `statusLiteral` | String | Yes | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | `redirectUrl` | String | No | A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **orderId**: '00000000-0000-0000-0000-000000000000' - **paymentId**: 'default' - **paymentStatus**: 'default' - **statusLiteral**: started ### Constant Properties `orderId` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Elastic Search Indexing `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Unique Properties `orderId` Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option. ### Secondary Key Properties `orderId` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Session Data Properties `ownerId` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **ownerId**: ID property will be mapped to the session parameter `userId`. This property is also used to store the owner of the session data, allowing for ownership checks and access control. ### Filter Properties `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled. - **ownerId**: ID has a filter named `ownerId` - **orderId**: ID has a filter named `orderId` - **paymentId**: String has a filter named `paymentId` - **paymentStatus**: String has a filter named `paymentStatus` - **statusLiteral**: String has a filter named `statusLiteral` - **redirectUrl**: String has a filter named `redirectUrl` ## sys_paymentCustomer Data Object ### Object Overview **Description:** A payment storage object to store the customer values of the payment platform This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `userId` | ID | No | An ID value to represent the user who is created as a stripe customer | | `customerId` | String | Yes | A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway | | `platform` | String | Yes | A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **customerId**: 'default' - **platform**: stripe ### Constant Properties `customerId` `platform` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `userId` `customerId` `platform` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Elastic Search Indexing `userId` `customerId` `platform` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `userId` `customerId` `platform` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Unique Properties `userId` `customerId` Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option. ### Secondary Key Properties `userId` `customerId` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Session Data Properties `userId` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **userId**: ID property will be mapped to the session parameter `userId`. This property is also used to store the owner of the session data, allowing for ownership checks and access control. ### Filter Properties `userId` `customerId` `platform` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled. - **userId**: ID has a filter named `userId` - **customerId**: String has a filter named `customerId` - **platform**: String has a filter named `platform` ## sys_paymentMethod Data Object ### Object Overview **Description:** A payment storage object to store the payment methods of the platform customers This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `paymentMethodId` | String | Yes | A string value to represent the id of the payment method on the payment platform. | | `userId` | ID | Yes | An ID value to represent the user who owns the payment method | | `customerId` | String | Yes | A string value to represent the customer id which is generated on the payment gateway. | | `cardHolderName` | String | No | A string value to represent the name of the card holder. It can be different than the registered customer. | | `cardHolderZip` | String | No | A string value to represent the zip code of the card holder. It is used for address verification in specific countries. | | `platform` | String | Yes | A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future. | | `cardInfo` | Object | Yes | A Json value to store the card details of the payment method. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **paymentMethodId**: 'default' - **userId**: '00000000-0000-0000-0000-000000000000' - **customerId**: 'default' - **platform**: stripe - **cardInfo**: {} ### Constant Properties `paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` `cardInfo` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Elastic Search Indexing `paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` `cardInfo` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `paymentMethodId` `userId` `customerId` `platform` `cardInfo` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Unique Properties `paymentMethodId` Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option. ### Secondary Key Properties `paymentMethodId` `userId` `customerId` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Session Data Properties `userId` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **userId**: ID property will be mapped to the session parameter `userId`. This property is also used to store the owner of the session data, allowing for ownership checks and access control. ### Filter Properties `paymentMethodId` `userId` `customerId` `cardHolderName` `cardHolderZip` `platform` `cardInfo` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled. - **paymentMethodId**: String has a filter named `paymentMethodId` - **userId**: ID has a filter named `userId` - **customerId**: String has a filter named `customerId` - **cardHolderName**: String has a filter named `cardHolderName` - **cardHolderZip**: String has a filter named `cardHolderZip` - **platform**: String has a filter named `platform` - **cardInfo**: Object has a filter named `cardInfo` ## Business Logic enrollmentManagement has got 26 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Create Enrollment](/document/businessLogic/createenrollment) * [Get Enrollment](/document/businessLogic/getenrollment) * [List Enrollments](/document/businessLogic/listenrollments) * [Create Refundrequest](/document/businessLogic/createrefundrequest) * [Get Refundrequest](/document/businessLogic/getrefundrequest) * [List Refundrequests](/document/businessLogic/listrefundrequests) * [Update Refundrequest](/document/businessLogic/updaterefundrequest) * [Cancel Enrollment](/document/businessLogic/cancelenrollment) * [Admin Refundenrollment](/document/businessLogic/adminrefundenrollment) * [Cascade Tutorban](/document/businessLogic/cascadetutorban) * [Cascade Courseremoval](/document/businessLogic/cascadecourseremoval) * [Cleanup Pendingenrollments](/document/businessLogic/cleanuppendingenrollments) * [Check Enrollmentcompletion](/document/businessLogic/checkenrollmentcompletion) * [Get Enrollmentpayment](/document/businessLogic/getenrollmentpayment) * [List Enrollmentpayments](/document/businessLogic/listenrollmentpayments) * [Create Enrollmentpayment](/document/businessLogic/createenrollmentpayment) * [Update Enrollmentpayment](/document/businessLogic/updateenrollmentpayment) * [Delete Enrollmentpayment](/document/businessLogic/deleteenrollmentpayment) * [Get Enrollmentpaymentbyorderid](/document/businessLogic/getenrollmentpaymentbyorderid) * [Get Enrollmentpaymentbypaymentid](/document/businessLogic/getenrollmentpaymentbypaymentid) * [Start Enrollmentpayment](/document/businessLogic/startenrollmentpayment) * [Refresh Enrollmentpayment](/document/businessLogic/refreshenrollmentpayment) * [Callback Enrollmentpayment](/document/businessLogic/callbackenrollmentpayment) * [Get Paymentcustomerbyuserid](/document/businessLogic/getpaymentcustomerbyuserid) * [List Paymentcustomers](/document/businessLogic/listpaymentcustomers) * [List Paymentcustomermethods](/document/businessLogic/listpaymentcustomermethods) ## Edge Controllers ### deletePaymentMethodEdge **Configuration:** - **Function Name**: `deletePaymentMethodEdge` - **Login Required**: Yes **REST Settings:** - **Path**: `/payment-methods/delete/:paymentMethodId` - **Method**: --- ### onRefundRequestCreated **Configuration:** - **Function Name**: `onRefundRequestCreated` - **Login Required**: No **REST Settings:** - **Path**: `` - **Method**: --- ### onEnrollmentPaymentDone **Configuration:** - **Function Name**: `onEnrollmentPaymentDone` - **Login Required**: No **REST Settings:** - **Path**: `` - **Method**: --- ## Service Library ### Functions #### getTutorProfileIdsByTutorId.js ```js module.exports = async function getTutorProfileIdsByTutorId(userId) { // Fetch all tutorProfiles for this user from tutorCatalog const { fetchRemoteListByMQuery } = require("serviceCommon"); const profiles = await fetchRemoteListByMQuery("tutorProfile", { tutorId: userId }); return profiles.map(p => p.id); } ``` #### validateEnrollmentConstraints.js ```js module.exports = function validateEnrollmentConstraints(coursePack, lessonSlotIds, screeningMeetings, studentId, tutorUser) { if (!coursePack) return { valid: false, error: 'Course pack not found.' }; // 1. Course moderation check if (coursePack.moderationStatus === 'removed') { return { valid: false, error: 'This course has been removed and is no longer available for enrollment.' }; } if (coursePack.moderationStatus === 'flagged') { return { valid: false, error: 'This course is currently under review and cannot accept new enrollments.' }; } if (coursePack.isPublished === false) { return { valid: false, error: 'This course is not currently published.' }; } // 2. Tutor status check if (tutorUser) { if (tutorUser.accountStatus === 'banned') { return { valid: false, error: 'This tutor\'s account has been suspended. Enrollment is not available.' }; } if (tutorUser.accountStatus === 'suspended') { return { valid: false, error: 'This tutor\'s account is temporarily suspended. Please try again later.' }; } } // 3. Screening check if (coursePack.preliminaryMeetingRequired) { const approved = (screeningMeetings || []).find( m => m.studentId === studentId && m.tutorDecision === 'approved' ); if (!approved) return { valid: false, error: 'Screening approval is required before enrollment.' }; } // lessonSlotIds is the array of IDs from the request const slots = Array.isArray(lessonSlotIds) ? lessonSlotIds : []; const slotCount = slots.length; if (slotCount === 0) return { valid: false, error: 'At least one lesson slot is required.' }; // 4. Required classes count if (coursePack.requiredClassesCount && slotCount !== coursePack.requiredClassesCount) { return { valid: false, error: `This course requires exactly ${coursePack.requiredClassesCount} classes. Got ${slotCount}.` }; } return { valid: true, error: null }; } ``` #### validateRefundEligibility.js ```js module.exports = function validateRefundEligibility(enrollment, lessonSlots, paymentRecord) { if (!enrollment) return { eligible: false, error: 'Enrollment not found.' }; // Must be an active enrollment if (enrollment.enrollmentStatus !== 'active') { return { eligible: false, error: 'Only active enrollments can be refunded.' }; } // Must have paid status if (enrollment.paymentStatus !== 'paid') { return { eligible: false, error: 'Only paid enrollments can be refunded.' }; } // Must not already be refunded if (enrollment.refundStatus === 'processed') { return { eligible: false, error: 'This enrollment has already been refunded.' }; } // Must have a valid payment record with paymentId for Stripe refund if (!paymentRecord || !paymentRecord.paymentId) { return { eligible: false, error: 'No payment record found for this enrollment. Cannot process refund.' }; } // Check lesson completion status const slots = lessonSlots || []; const completedSlots = slots.filter(s => s.status === 'completed'); // --- PATH 1: Within 1 hour of enrollment → auto-approved instant refund --- const enrolledAt = enrollment.enrolledAt || enrollment.createdAt; const enrollmentTime = enrolledAt ? new Date(enrolledAt).getTime() : 0; const now = Date.now(); const oneHourMs = 60 * 60 * 1000; const withinOneHour = enrollmentTime > 0 && (now - enrollmentTime) <= oneHourMs; if (withinOneHour) { return { eligible: true, error: null, refundType: 'autoApproved', firstLessonCompleted: completedSlots.length >= 1, stripePaymentIntentId: paymentRecord.paymentId, refundAmount: enrollment.totalAmount, currency: enrollment.currency }; } // --- PATH 2: After first lesson completed (exactly 1) → pending admin review --- if (completedSlots.length === 1) { return { eligible: true, error: null, refundType: 'pendingReview', firstLessonCompleted: true, stripePaymentIntentId: paymentRecord.paymentId, refundAmount: enrollment.totalAmount, currency: enrollment.currency }; } // --- DENIED: No lessons completed (past 1 hour) --- if (completedSlots.length === 0) { return { eligible: false, error: 'The 1-hour instant refund window has passed. Refund is available after your first lesson is completed.' }; } // --- DENIED: More than 1 lesson completed --- return { eligible: false, error: 'Refund is no longer available after more than one lesson has been completed.' }; } ``` #### cancelEnrollmentLessonSlots.js ```js module.exports = async function cancelEnrollmentLessonSlots(lessonSlotIds, session) { if (!lessonSlotIds || !Array.isArray(lessonSlotIds) || lessonSlotIds.length === 0) { return { canceled: 0, errors: [] }; } const axios = require('axios'); const { getServiceSecret } = require('common'); // Build the courseScheduling M2M URL // In preview, services are on the same host with different routes const baseUrl = process.env.COURSESCHEDULING_API_URL || 'http://localhost:3002'; const m2mUrl = `${baseUrl}/m2m/updateLessonSlotById`; const serviceSecret = getServiceSecret ? getServiceSecret() : process.env.SERVICE_SECRET_KEY; let canceled = 0; const errors = []; for (const slotId of lessonSlotIds) { try { await axios.patch(m2mUrl, { id: slotId, dataClause: { status: 'canceled' } }, { headers: { 'Content-Type': 'application/json', ...(serviceSecret ? { 'x-service-secret': serviceSecret } : {}), ...(session?.token ? { 'Authorization': `Bearer ${session.token}` } : {}) }, timeout: 5000 }); canceled++; } catch (err) { errors.push({ slotId, error: err.message }); } } return { canceled, total: lessonSlotIds.length, errors }; } ``` #### cancelAllTutorEnrollments.js ```js module.exports = async function cancelAllTutorEnrollments(tutorProfileId, reason, session) { const { updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); const userQuery = { $and: [ { tutorProfileId: tutorProfileId }, { enrollmentStatus: 'active' }, { isActive: true } ] }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('enrollment'); const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; if (enrollments.length === 0) { return { canceled: 0, total: 0, errors: [], affectedStudentIds: [] }; } const context = { session, requestId: 'cascade-tutor-ban' }; let canceled = 0; const errors = []; const affectedStudentIds = []; for (const enrollment of enrollments) { try { await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'canceled', paymentStatus: 'refunded', refundStatus: 'processed' }, context); if (enrollment.studentId) affectedStudentIds.push(enrollment.studentId); if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) { try { const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots'); await cancelSlots(enrollment.lessonSlotIds, session); } catch (slotErr) { console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message); } } canceled++; } catch (err) { errors.push({ enrollmentId: enrollment.id, error: err.message }); } } return { canceled, total: enrollments.length, errors, affectedStudentIds: [...new Set(affectedStudentIds)] }; } ``` #### cancelAllCourseEnrollments.js ```js module.exports = async function cancelAllCourseEnrollments(coursePackId, reason, session) { const { updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); const userQuery = { $and: [ { coursePackId: coursePackId }, { enrollmentStatus: 'active' }, { isActive: true } ] }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('enrollment'); const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; if (enrollments.length === 0) { return { canceled: 0, total: 0, errors: [], affectedStudentIds: [] }; } const context = { session, requestId: 'cascade-course-removal' }; let canceled = 0; const errors = []; const affectedStudentIds = []; for (const enrollment of enrollments) { try { await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'canceled', paymentStatus: 'refunded', refundStatus: 'processed' }, context); if (enrollment.studentId) affectedStudentIds.push(enrollment.studentId); if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) { try { const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots'); await cancelSlots(enrollment.lessonSlotIds, session); } catch (slotErr) { console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message); } } canceled++; } catch (err) { errors.push({ enrollmentId: enrollment.id, error: err.message }); } } return { canceled, total: enrollments.length, errors, affectedStudentIds: [...new Set(affectedStudentIds)] }; } ``` #### cleanupPendingEnrollments.js ```js module.exports = async function cleanupPendingEnrollments(maxAgeMinutes, session) { const { updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); const cutoff = new Date(Date.now() - (maxAgeMinutes || 60) * 60 * 1000).toISOString(); // Find pending enrollments older than cutoff const userQuery = { $and: [ { enrollmentStatus: 'pending' }, { paymentStatus: 'pending' }, { createdAt: { $lt: cutoff } }, { isActive: true } ] }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('enrollment'); const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; if (enrollments.length === 0) { return { cleaned: 0, total: 0, errors: [] }; } const context = { session: session || {}, requestId: 'cleanup-pending-enrollments' }; let cleaned = 0; const errors = []; for (const enrollment of enrollments) { try { // Cancel the enrollment await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'canceled', refundStatus: 'ineligible' }, context); // Free lesson slots if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) { try { const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots'); await cancelSlots(enrollment.lessonSlotIds, session); } catch (slotErr) { console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message); } } cleaned++; } catch (err) { errors.push({ enrollmentId: enrollment.id, error: err.message }); } } return { cleaned, total: enrollments.length, errors }; } ``` #### checkEnrollmentCompletion.js ```js module.exports = async function checkEnrollmentCompletion(enrollmentId, session) { const { getEnrollmentById, updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); if (!enrollmentId) return { updated: false, reason: 'No enrollmentId' }; // Fetch the enrollment const enrollment = await getEnrollmentById(enrollmentId); if (!enrollment) return { updated: false, reason: 'Enrollment not found' }; if (enrollment.enrollmentStatus !== 'active') return { updated: false, reason: 'Not active' }; const slotIds = enrollment.lessonSlotIds; if (!slotIds || !Array.isArray(slotIds) || slotIds.length === 0) { return { updated: false, reason: 'No lesson slots' }; } // Fetch all lesson slots from Elasticsearch const userQuery = { id: { $in: slotIds } }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('lessonSlot'); const slots = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; // Check if ALL slots are completed const allCompleted = slots.length > 0 && slots.length === slotIds.length && slots.every(s => s.status === 'completed'); if (!allCompleted) { return { updated: false, reason: `${slots.filter(s => s.status === 'completed').length}/${slotIds.length} completed` }; } // Mark enrollment as completed const context = { session: session || {}, requestId: 'auto-complete-enrollment' }; await updateEnrollmentById(enrollmentId, { enrollmentStatus: 'completed' }, context); return { updated: true, enrollmentId }; } ``` #### publishEnrichedRefundEvent.js ```js module.exports = async function publishEnrichedRefundEvent(refundRequest, enrollment) { const { elasticClient, sendMessageToKafka } = require('common'); let student = null; let tutorUser = null; let coursePack = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source; const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } }); const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null; if (profile && profile.tutorId) { const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } }); if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source; } const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category'], size: 1 } }); if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source; } catch (err) { console.log('Warning: failed to fetch refund notification data from ES:', err.message); } const enrichedPayload = { id: refundRequest.id, enrollmentId: refundRequest.enrollmentId, status: refundRequest.status, reason: refundRequest.reason, requestedAt: refundRequest.requestedAt, processedAt: refundRequest.processedAt, totalAmount: enrollment.totalAmount, currency: enrollment.currency, student: student, tutorUser: tutorUser, coursePack: coursePack }; try { const topic = refundRequest.status === 'autoApproved' ? 'tutorhub-enrollmentmanagement-service-refund-processed' : 'tutorhub-enrollmentmanagement-service-refund-requested'; await sendMessageToKafka(topic, enrichedPayload); } catch (err) { console.log('Warning: failed to publish enriched refund event:', err.message); } } ``` ### Edge Functions #### deletePaymentMethodEdge.js ```js const { getSys_paymentMethodByPaymentMethodId, deleteSys_paymentMethodById } = require('dbLayer'); const { stripeGateway } = require('common'); module.exports = async (request) => { const session = request.session; const paymentMethodId = request.params.paymentMethodId; if (!paymentMethodId) { return { status: 400, result: 'ERR', message: 'paymentMethodId is required' }; } const paymentMethodData = await getSys_paymentMethodByPaymentMethodId(paymentMethodId); if (!paymentMethodData) { return { status: 404, result: 'ERR', message: 'Payment method not found' }; } if (paymentMethodData.userId !== session.userId) { return { status: 403, result: 'ERR', message: 'Not authorized to delete this payment method' }; } try { if (Object.keys(stripeGateway).length > 0) { await stripeGateway.deletePaymentMethod(paymentMethodId); } } catch (stripeErr) { console.log('Stripe detach warning (proceeding with local delete):', stripeErr.message); } const deleted = await deleteSys_paymentMethodById(paymentMethodData.id); if (!deleted) { return { status: 500, result: 'ERR', message: 'Failed to delete payment method record' }; } return { status: 200, result: 'OK', message: 'Payment method deleted', data: deleted }; }; ``` #### onEnrollmentPaymentDone.js ```js const { updateEnrollmentById } = require('dbLayer'); const { elasticClient, sendMessageToKafka } = require('common'); module.exports = async (request) => { const enrollment = request.enrollment; if (!enrollment || !enrollment.id) return { status: 200, message: 'No enrollment to update' }; await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'active', enrolledAt: new Date().toISOString() }); let student = null; let tutorUser = null; let coursePack = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source; const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } }); const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null; if (profile && profile.tutorId) { const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } }); if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source; } const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category', 'schedulingType'], size: 1 } }); if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source; } catch (err) { console.log('Warning: failed to fetch notification data from ES:', err.message); } try { await sendMessageToKafka('tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed', { id: enrollment.id, studentId: enrollment.studentId, coursePackId: enrollment.coursePackId, tutorProfileId: enrollment.tutorProfileId, totalAmount: enrollment.totalAmount, currency: enrollment.currency, student: student, tutorUser: tutorUser, coursePack: coursePack }); } catch (err) { console.log('Warning: failed to publish enriched enrollment event:', err.message); } return { status: 200, message: 'Enrollment activated' }; }; ``` #### onRefundRequestCreated.js ```js const { getEnrollmentById } = require('dbLayer'); const { elasticClient, sendMessageToKafka } = require('common'); module.exports = async (request) => { const payload = request.body || request.kafkaMessage || request; const dataSource = payload.dataSource || payload; if (!dataSource || !dataSource.enrollmentId) { console.log('onRefundRequestCreated: no enrollmentId in payload, skipping'); return { status: 200, message: 'Skipped - no enrollmentId' }; } const refundRequest = dataSource; let enrollment = null; try { enrollment = await getEnrollmentById(refundRequest.enrollmentId); } catch (err) { console.log('onRefundRequestCreated: failed to fetch enrollment:', err.message); return { status: 200, message: 'Skipped - enrollment not found' }; } if (!enrollment) { console.log('onRefundRequestCreated: enrollment not found for', refundRequest.enrollmentId); return { status: 200, message: 'Skipped - enrollment not found' }; } let student = null; let tutorUser = null; let coursePack = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source; const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } }); const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null; if (profile && profile.tutorId) { const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } }); if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source; } const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category'], size: 1 } }); if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source; } catch (err) { console.log('onRefundRequestCreated: failed to fetch enrichment data from ES:', err.message); } const enrichedPayload = { id: refundRequest.id, enrollmentId: refundRequest.enrollmentId, status: refundRequest.status, reason: refundRequest.reason, requestedAt: refundRequest.requestedAt, processedAt: refundRequest.processedAt, totalAmount: enrollment.totalAmount, currency: enrollment.currency, student: student, tutorUser: tutorUser, coursePack: coursePack }; try { const isAutoApproved = refundRequest.status === 'autoApproved' || refundRequest.status === 'autoapproved'; const topic = isAutoApproved ? 'tutorhub-enrollmentmanagement-service-refund-processed' : 'tutorhub-enrollmentmanagement-service-refund-requested'; await sendMessageToKafka(topic, enrichedPayload); console.log('onRefundRequestCreated: published to', topic); } catch (err) { console.log('onRefundRequestCreated: failed to publish enriched refund event:', err.message); } return { status: 200, message: 'Refund notification published' }; }; ``` --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## tutorhub-enrollmentmanagement-service **Version:** `1.0.76` Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. ## 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 EnrollmentManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our EnrollmentManagement Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the EnrollmentManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying EnrollmentManagement 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 EnrollmentManagement 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 EnrollmentManagement 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 | tutorhub-access-token| | Cookie | tutorhub-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 EnrollmentManagement 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 EnrollmentManagement service. This service is configured to listen for HTTP requests on port `3003`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api` * **Production:** `https://tutorhub.mindbricks.co/enrollmentmanagement-api` **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 EnrollmentManagement 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 `EnrollmentManagement` 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 `EnrollmentManagement` 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 `EnrollmentManagement` 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 EnrollmentManagement 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. ### Enrollment resource *Resource Definition* : Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. *Enrollment Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to purchased course pack.* | | **studentId** | ID | | | *FK to enrolling student (auth:user).* | | **tutorProfileId** | ID | | | *FK to the course's tutorProfile for admin/analytics.* | | **lessonSlotIds** | ID | | | *IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot).* | | **totalAmount** | Double | | | *Total amount paid for enrollment (for all slots/pack, pre-promotion/refund).* | | **currency** | String | | | *3-letter ISO currency code (e.g., 'USD', 'EUR').* | | **paymentStatus** | Enum | | | *Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation).* | | **refundStatus** | Enum | | | *Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow.* | | **enrollmentStatus** | Enum | | | *Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated).* | | **enrolledAt** | Date | | | *Datetime of completed enrollment (post-payment).* | | **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. ##### paymentStatus Enum Property *Property Definition* : Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **paid** | `"paid""` | 1 | | **refunded** | `"refunded""` | 2 | ##### refundStatus Enum Property *Property Definition* : Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **notRequested** | `"notRequested""` | 0 | | **eligible** | `"eligible""` | 1 | | **processed** | `"processed""` | 2 | | **ineligible** | `"ineligible""` | 3 | ##### enrollmentStatus Enum Property *Property Definition* : Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **active** | `"active""` | 1 | | **completed** | `"completed""` | 2 | | **canceled** | `"canceled""` | 3 | ##### 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 | ### RefundRequest resource *Resource Definition* : A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. *RefundRequest Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **enrollmentId** | ID | | | *FK to enrollment object for which refund is being requested (unique: one refund per enrollment).* | | **requestedBy** | ID | | | *User (student) making the refund request (auth:user id).* | | **requestedAt** | Date | | | *Datetime refund was requested.* | | **processedAt** | Date | | | *When refund was processed by system (auto-approval).* | | **status** | Enum | | | *Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly).* | | **reason** | String | | | *User-supplied reason for requesting refund.* | | **firstLessonCompleted** | Boolean | | | *True if this refund is after first lesson (enforced by workflow); must be checked before approval.* | | **adminNote** | String | | | *Admin note explaining the refund decision (approve/reject reason).* | #### 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* : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | | **autoApproved** | `"autoApproved""` | 3 | ### Sys_enrollmentPayment resource *Resource Definition* : A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object's checkout config *Sys_enrollmentPayment 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 enrollment 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 Enrollment` API **[Default create API]** — This is the designated default `create` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Creates a new enrollment for a student in a selected course pack and selected lesson slots. Enforces booking prerequisites (availability, non-duplication, preliminary meeting if flagged in coursePack), and triggers Stripe payment. Updates all associated lesson slot statuses to booked. Enrollment remains pending until payment confirmed by Stripe webhook. **API Frontend Description By The Backend Architect** Student chooses course pack, selects lesson slots, triggers enrollment and Stripe payment. If the course requires preliminary screening, checks that it was passed before proceeding. If payment fails, booking is not confirmed. Successful booking sets lesson slots status to 'booked' and opens enrollment. Student, tutor, and admin can see details. **Rest Route** The `createEnrollment` API REST controller can be triggered via the following route: `/v1/enrollments` **Rest Request Parameters** The `createEnrollment` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | lessonSlotIds | ID | true | request.body?.["lessonSlotIds"] | | totalAmount | Double | true | request.body?.["totalAmount"] | | currency | String | true | request.body?.["currency"] | | refundStatus | Enum | true | request.body?.["refundStatus"] | | enrolledAt | Date | false | request.body?.["enrolledAt"] | **coursePackId** : FK to purchased course pack. **tutorProfileId** : FK to the course's tutorProfile for admin/analytics. **lessonSlotIds** : IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). **totalAmount** : Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). **currency** : 3-letter ISO currency code (e.g., 'USD', 'EUR'). **refundStatus** : Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. **enrolledAt** : Datetime of completed enrollment (post-payment). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/enrollments** ```js axios({ method: 'POST', url: '/v1/enrollments', data: { coursePackId:"ID", tutorProfileId:"ID", lessonSlotIds:"ID", totalAmount:"Double", currency:"String", refundStatus:"Enum", enrolledAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Enrollment` API **[Default get API]** — This is the designated default `get` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single enrollment, including all details and linked objects (student, coursePack, lessonSlots). Only the enrollment's student, tutor, or admin may view. **API Frontend Description By The Backend Architect** Enrollment owners (student), relevant tutor, and admin can see all details of an enrollment via this API. Contains lesson slot list, linked pack, payment/refund status, fulfillment states for transparency. **Rest Route** The `getEnrollment` API REST controller can be triggered via the following route: `/v1/enrollments/:enrollmentId` **Rest Request Parameters** The `getEnrollment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | **enrollmentId** : 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/enrollments/:enrollmentId** ```js axios({ method: 'GET', url: `/v1/enrollments/${enrollmentId}`, 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": "enrollment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "enrollment": { "coursePack": { "tutorProfileId": "ID", "title": "String", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer" }, "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String" }, {}, {} ], "student": { "fullname": "String", "avatar": "String" }, "tutorProfile": { "tutorId": "ID", "certifications": "String", "bio": "Text", "profilePhoto": "String" }, "isActive": true } } ``` ### `List Enrollments` API **[Default list API]** — This is the designated default `list` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all enrollments. Admin sees all; students see their enrollments; tutors see enrollments where their tutorProfileId matches. **API Frontend Description By The Backend Architect** Admins see all enrollments; students see their own; tutors can filter enrollments to their packs by tutorProfileId. Response is enriched with embedded course, lesson, and user details as requested by the frontend. **Rest Route** The `listEnrollments` API REST controller can be triggered via the following route: `/v1/enrollments` **Rest Request Parameters** The `listEnrollments` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | false | request.query?.["tutorProfileId"] | **tutorProfileId** : Optional tutor profile ID filter for tutors to see enrollments in their courses. **Filter Parameters** The `listEnrollments` api supports 1 optional filter parameter for filtering list results: **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/enrollments** ```js axios({ method: 'GET', url: '/v1/enrollments', data: { }, params: { tutorProfileId:'"ID"', // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "coursePack": [ { "title": "String", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "isActive": true }, {}, {} ], "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer" }, {}, {} ], "student": [ { "email": "String", "fullname": "String", "avatar": "String" }, {}, {} ], "tutorProfile": [ { "tutorId": "ID", "bio": "Text" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Refundrequest` API **[Default create API]** — This is the designated default `create` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student files refund request for a completed enrollment only after first lesson and only if no additional lessons are complete. Auto-approves, updates enrollment statuses, and triggers Stripe refund if eligible. **API Frontend Description By The Backend Architect** Students can trigger a refund for their enrollment only after first lesson, provided no additional lessons have been completed. The refund is auto-approved and reflected in both user's and admin's views; tutor and admin are notified. No manual approval or asynchronous queue, strictly within narrow business criteria. **Rest Route** The `createRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests` **Rest Request Parameters** The `createRefundRequest` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.body?.["enrollmentId"] | | requestedAt | Date | true | request.body?.["requestedAt"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | true | request.body?.["status"] | | reason | String | true | request.body?.["reason"] | | firstLessonCompleted | Boolean | true | request.body?.["firstLessonCompleted"] | | adminNote | String | false | request.body?.["adminNote"] | **enrollmentId** : FK to enrollment object for which refund is being requested (unique: one refund per enrollment). **requestedAt** : Datetime refund was requested. **processedAt** : When refund was processed by system (auto-approval). **status** : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). **reason** : User-supplied reason for requesting refund. **firstLessonCompleted** : True if this refund is after first lesson (enforced by workflow); must be checked before approval. **adminNote** : Admin note explaining the refund decision (approve/reject reason). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/refundrequests** ```js axios({ method: 'POST', url: '/v1/refundrequests', data: { enrollmentId:"ID", requestedAt:"Date", processedAt:"Date", status:"Enum", reason:"String", firstLessonCompleted:"Boolean", adminNote:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Refundrequest` API **[Default get API]** — This is the designated default `get` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get refund request record for audit—visible to student (their own), tutor (if their course), or admin. Linked enrollment, user, and status are included. **API Frontend Description By The Backend Architect** Students check status of their refund request; tutors may audit if linked to their courses; admins can view all. Details include enrollment and state for auditing. **Rest Route** The `getRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests/:refundRequestId` **Rest Request Parameters** The `getRefundRequest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | **refundRequestId** : 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/refundrequests/:refundRequestId** ```js axios({ method: 'GET', url: `/v1/refundrequests/${refundRequestId}`, 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": "refundRequest", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "refundRequest": { "enrollment": { "coursePackId": "ID", "studentId": "ID" }, "isActive": true } } ``` ### `List Refundrequests` API **[Default list API]** — This is the designated default `list` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all refund requests (students see their own, admins see all, tutors see linked to their courses via coursePack). **API Frontend Description By The Backend Architect** Admins list all refund requests; students see their submitted refunds; tutors see those linked to their courses for reporting and audit. Each item shows enrollment link and high-level audit fields. **Rest Route** The `listRefundRequests` API REST controller can be triggered via the following route: `/v1/refundrequests` **Rest Request Parameters** The `listRefundRequests` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/refundrequests** ```js axios({ method: 'GET', url: '/v1/refundrequests', 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": "refundRequests", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "refundRequests": [ { "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "totalAmount": "Double", "currency": "String" }, {}, {} ], "coursePack": { "title": "String" }, "requester": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Refundrequest` API **[Default update API]** — This is the designated default `update` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin updates a refund request: approve or reject with an admin note. Only admins can update refund requests. **API Frontend Description By The Backend Architect** Admin-only endpoint for processing pending refund requests. Admin sets status to approved or rejected and optionally provides an adminNote explaining the decision. processedAt is set automatically on approval/rejection. **Rest Route** The `updateRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests/:refundRequestId` **Rest Request Parameters** The `updateRefundRequest` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | **refundRequestId** : This id paremeter is used to select the required data object that will be updated **processedAt** : When refund was processed by system (auto-approval). **status** : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). **adminNote** : Admin note explaining the refund decision (approve/reject reason). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refundrequests/:refundRequestId** ```js axios({ method: 'PATCH', url: `/v1/refundrequests/${refundRequestId}`, data: { processedAt:"Date", status:"Enum", adminNote:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Cancel Enrollment` API Admin force-cancels an enrollment. Sets enrollmentStatus to canceled, paymentStatus to refunded, refundStatus to processed. Used when a tutor is banned/suspended or a course is removed. **API Frontend Description By The Backend Architect** Admin-only action to force-cancel an enrollment. Used when tutor is banned, suspended, or course is removed. **Rest Route** The `cancelEnrollment` API REST controller can be triggered via the following route: `/v1/cancelenrollment/:enrollmentId` **Rest Request Parameters** The `cancelEnrollment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | cancelReason | String | | request.body?.["cancelReason"] | **enrollmentId** : This id paremeter is used to select the required data object that will be updated **cancelReason** : Admin reason for canceling the enrollment **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/cancelenrollment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/cancelenrollment/${enrollmentId}`, data: { cancelReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Admin Refundenrollment` API Admin-initiated refund for an enrollment. Creates a refundRequest with autoApproved status, cancels the enrollment, and triggers Stripe refund. No student eligibility checks — admin override. **API Frontend Description By The Backend Architect** Admin-only action to refund an enrollment on behalf of a student. Used when tutor is banned/suspended, course removed, or admin decides a refund is warranted. The enrollment is immediately canceled and a refund request record is created for audit. **Rest Route** The `adminRefundEnrollment` API REST controller can be triggered via the following route: `/v1/adminrefundenrollment` **Rest Request Parameters** The `adminRefundEnrollment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | | reason | String | | request.body?.["reason"] | **enrollmentId** : The enrollment to refund **reason** : Admin reason for issuing the refund **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminrefundenrollment** ```js axios({ method: 'POST', url: '/v1/adminrefundenrollment', data: { enrollmentId:"ID", reason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Cascade Tutorban` API Admin cascade: cancel all active enrollments for a banned/suspended tutor. **API Frontend Description By The Backend Architect** Called after admin bans or suspends a tutor. Cancels all active enrollments and frees slots. **Rest Route** The `cascadeTutorBan` API REST controller can be triggered via the following route: `/v1/cascadetutorban` **Rest Request Parameters** The `cascadeTutorBan` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | reason | String | | request.body?.["reason"] | **tutorProfileId** : The tutor profile whose enrollments should be canceled **reason** : Reason for cascade cancellation **Filter Parameters** The `cascadeTutorBan` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/cascadetutorban** ```js axios({ method: 'POST', url: '/v1/cascadetutorban', data: { tutorProfileId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Cascade Courseremoval` API Admin cascade: cancel all active enrollments for a removed course pack. **API Frontend Description By The Backend Architect** Called after admin removes a course. Cancels all active enrollments and frees slots. **Rest Route** The `cascadeCourseRemoval` API REST controller can be triggered via the following route: `/v1/cascadecourseremoval` **Rest Request Parameters** The `cascadeCourseRemoval` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | | request.body?.["coursePackId"] | | reason | String | | request.body?.["reason"] | **coursePackId** : The course pack whose enrollments should be canceled **reason** : Reason for cascade cancellation **Filter Parameters** The `cascadeCourseRemoval` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/cascadecourseremoval** ```js axios({ method: 'POST', url: '/v1/cascadecourseremoval', data: { coursePackId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Cleanup Pendingenrollments` API Cleanup stale pending enrollments that were never paid. Cancels them and frees lesson slots. Default timeout: 60 minutes. **API Frontend Description By The Backend Architect** Admin or system cron calls this to clean up abandoned enrollments. Can also be triggered from frontend as a housekeeping action. **Rest Route** The `cleanupPendingEnrollments` API REST controller can be triggered via the following route: `/v1/cleanuppendingenrollments` **Rest Request Parameters** The `cleanupPendingEnrollments` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | maxAgeMinutes | Integer | | request.body?.["maxAgeMinutes"] | **maxAgeMinutes** : How old (in minutes) a pending enrollment must be to get cleaned up. Default: 60 **Filter Parameters** The `cleanupPendingEnrollments` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/cleanuppendingenrollments** ```js axios({ method: 'POST', url: '/v1/cleanuppendingenrollments', data: { maxAgeMinutes:"Integer", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Check Enrollmentcompletion` API Check if all lesson slots in an enrollment are completed and mark enrollment as completed if so. **API Frontend Description By The Backend Architect** Called after a lesson is marked completed. Checks if all lessons are done and auto-completes the enrollment. **Rest Route** The `checkEnrollmentCompletion` API REST controller can be triggered via the following route: `/v1/checkenrollmentcompletion` **Rest Request Parameters** The `checkEnrollmentCompletion` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | **enrollmentId** : The enrollment to check for completion **Filter Parameters** The `checkEnrollmentCompletion` api supports 1 optional filter parameter for filtering list results: **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 **POST /v1/checkenrollmentcompletion** ```js axios({ method: 'POST', url: '/v1/checkenrollmentcompletion', data: { enrollmentId:"ID", }, params: { // Filter parameters (see Filter Parameters section above) // 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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": [] } ``` ### `Get Enrollmentpayment` API This route is used to get the payment information by ID. **Rest Route** The `getEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `getEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | **sys_enrollmentPaymentId** : 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayments` API This route is used to list all payments. **Rest Route** The `listEnrollmentPayments` API REST controller can be triggered via the following route: `/v1/enrollmentpayments` **Rest Request Parameters** **Filter Parameters** The `listEnrollmentPayments` 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 enrollment 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/enrollmentpayments** ```js axios({ method: 'GET', url: '/v1/enrollmentpayments', 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_enrollmentPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_enrollmentPayments": [ { "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 Enrollmentpayment` API This route is used to create a new payment. **Rest Route** The `createEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment` **Rest Request Parameters** The `createEnrollmentPayment` 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 enrollment 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/enrollmentpayment** ```js axios({ method: 'POST', url: '/v1/enrollmentpayment', 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_enrollmentPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` API This route is used to update an existing payment. **Rest Route** The `updateEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `updateEnrollmentPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | | 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_enrollmentPaymentId** : 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'PATCH', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` API This route is used to delete a payment. **Rest Route** The `deleteEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `deleteEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | **sys_enrollmentPaymentId** : 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'DELETE', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getEnrollmentPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/enrollmentpaymentbyorderid/:orderId` **Rest Request Parameters** The `getEnrollmentPaymentByOrderId` 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 enrollment 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/enrollmentpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbyorderid/${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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getEnrollmentPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/enrollmentpaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getEnrollmentPaymentByPaymentId` 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/enrollmentpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbypaymentid/${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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` API Start payment for enrollment **Rest Route** The `startEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/startenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `startEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **enrollmentId** : 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/startenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/startenrollmentpayment/${enrollmentId}`, 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 Enrollmentpayment` API Refresh payment info for enrollment from Stripe **Rest Route** The `refreshEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/refreshenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `refreshEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **enrollmentId** : 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/refreshenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/refreshenrollmentpayment/${enrollmentId}`, 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 Enrollmentpayment` API Refresh payment values by gateway webhook call for enrollment **Rest Route** The `callbackEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/callbackenrollmentpayment` **Rest Request Parameters** The `callbackEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | false | request.body?.["enrollmentId"] | **enrollmentId** : 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/callbackenrollmentpayment** ```js axios({ method: 'POST', url: '/v1/callbackenrollmentpayment', data: { enrollmentId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 ## tutorhub-enrollmentmanagement-service Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. ## 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 `EnrollmentManagement` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `EnrollmentManagement` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `EnrollmentManagement` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `EnrollmentManagement` 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 `EnrollmentManagement` 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 enrollment-created **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-enrollment-created` This event is triggered upon the creation of a `enrollment` 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","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent enrollment-updated **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-enrollment-updated` Activation of this event follows the update of a `enrollment` data object. The payload contains the updated information under the `enrollment` attribute, along with the original data prior to update, labeled as `old_enrollment` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_enrollment:{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, enrollment:{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent enrollment-deleted **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-enrollment-deleted` This event announces the deletion of a `enrollment` 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","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent refundRequest-created **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-refundrequest-created` This event is triggered upon the creation of a `refundRequest` 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","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent refundRequest-updated **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-refundrequest-updated` Activation of this event follows the update of a `refundRequest` data object. The payload contains the updated information under the `refundRequest` attribute, along with the original data prior to update, labeled as `old_refundRequest` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_refundRequest:{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, refundRequest:{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent refundRequest-deleted **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-refundrequest-deleted` This event announces the deletion of a `refundRequest` 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","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent sys_enrollmentPayment-created **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-sys_enrollmentpayment-created` This event is triggered upon the creation of a `sys_enrollmentPayment` 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_enrollmentPayment-updated **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-sys_enrollmentpayment-updated` Activation of this event follows the update of a `sys_enrollmentPayment` data object. The payload contains the updated information under the `sys_enrollmentPayment` attribute, along with the original data prior to update, labeled as `old_sys_enrollmentPayment` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_sys_enrollmentPayment:{"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_enrollmentPayment:{"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_enrollmentPayment-deleted **Event topic**: `tutorhub-enrollmentmanagement-service-dbevent-sys_enrollmentpayment-deleted` This event announces the deletion of a `sys_enrollmentPayment` 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**: `tutorhub-enrollmentmanagement-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**: `tutorhub-enrollmentmanagement-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**: `tutorhub-enrollmentmanagement-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**: `tutorhub-enrollmentmanagement-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**: `tutorhub-enrollmentmanagement-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**: `tutorhub-enrollmentmanagement-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 `EnrollmentManagement` 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 enrollment-created **Event topic**: `elastic-index-tutorhub_enrollment-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event enrollment-updated **Event topic**: `elastic-index-tutorhub_enrollment-created` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event enrollment-deleted **Event topic**: `elastic-index-tutorhub_enrollment-deleted` **Event payload**: ```json {"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event enrollment-extended **Event topic**: `elastic-index-tutorhub_enrollment-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 enrollment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** 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":"enrollment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundrequest-created **Event topic** : `tutorhub-enrollmentmanagement-service-refundrequest-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 `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event enrollment-canceled **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundenrollment-admined **Event topic** : `tutorhub-enrollmentmanagement-service-refundenrollment-admined` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorban-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-tutorban-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event courseremoval-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-courseremoval-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event enrollmentpayment-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayments-listed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayments-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_enrollmentPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayments`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_enrollmentPayments":[{"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 enrollmentpayment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** 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_enrollmentPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-updated **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-deleted **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbyorderid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbyorderid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbypaymentid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbypaymentid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-started **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-refreshed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-calledback **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"POST","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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 refundrequest-created **Event topic**: `elastic-index-tutorhub_refundrequest-created` **Event payload**: ```json {"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event refundrequest-updated **Event topic**: `elastic-index-tutorhub_refundrequest-created` **Event payload**: ```json {"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event refundrequest-deleted **Event topic**: `elastic-index-tutorhub_refundrequest-deleted` **Event payload**: ```json {"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event refundrequest-extended **Event topic**: `elastic-index-tutorhub_refundrequest-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 enrollment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** 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":"enrollment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundrequest-created **Event topic** : `tutorhub-enrollmentmanagement-service-refundrequest-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 `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event enrollment-canceled **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundenrollment-admined **Event topic** : `tutorhub-enrollmentmanagement-service-refundenrollment-admined` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorban-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-tutorban-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event courseremoval-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-courseremoval-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event enrollmentpayment-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayments-listed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayments-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_enrollmentPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayments`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_enrollmentPayments":[{"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 enrollmentpayment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** 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_enrollmentPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-updated **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-deleted **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbyorderid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbyorderid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbypaymentid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbypaymentid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-started **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-refreshed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-calledback **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"POST","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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_enrollmentpayment-created **Event topic**: `elastic-index-tutorhub_sys_enrollmentpayment-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_enrollmentpayment-updated **Event topic**: `elastic-index-tutorhub_sys_enrollmentpayment-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_enrollmentpayment-deleted **Event topic**: `elastic-index-tutorhub_sys_enrollmentpayment-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_enrollmentpayment-extended **Event topic**: `elastic-index-tutorhub_sys_enrollmentpayment-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 enrollment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** 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":"enrollment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundrequest-created **Event topic** : `tutorhub-enrollmentmanagement-service-refundrequest-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 `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event enrollment-canceled **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundenrollment-admined **Event topic** : `tutorhub-enrollmentmanagement-service-refundenrollment-admined` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorban-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-tutorban-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event courseremoval-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-courseremoval-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event enrollmentpayment-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayments-listed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayments-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_enrollmentPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayments`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_enrollmentPayments":[{"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 enrollmentpayment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** 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_enrollmentPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-updated **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-deleted **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbyorderid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbyorderid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbypaymentid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbypaymentid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-started **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-refreshed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-calledback **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"POST","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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-tutorhub_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-tutorhub_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-tutorhub_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-tutorhub_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 enrollment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** 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":"enrollment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundrequest-created **Event topic** : `tutorhub-enrollmentmanagement-service-refundrequest-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 `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event enrollment-canceled **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundenrollment-admined **Event topic** : `tutorhub-enrollmentmanagement-service-refundenrollment-admined` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorban-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-tutorban-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event courseremoval-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-courseremoval-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event enrollmentpayment-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayments-listed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayments-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_enrollmentPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayments`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_enrollmentPayments":[{"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 enrollmentpayment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** 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_enrollmentPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-updated **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-deleted **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbyorderid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbyorderid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbypaymentid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbypaymentid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-started **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-refreshed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-calledback **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"POST","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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-tutorhub_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-tutorhub_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-tutorhub_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-tutorhub_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 enrollment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** 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":"enrollment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundrequest-created **Event topic** : `tutorhub-enrollmentmanagement-service-refundrequest-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 `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event enrollment-canceled **Event topic** : `tutorhub-enrollmentmanagement-service-enrollment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event refundenrollment-admined **Event topic** : `tutorhub-enrollmentmanagement-service-refundenrollment-admined` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `refundRequest` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`refundRequest`** 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":"refundRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"refundRequest":{"id":"ID","enrollmentId":"ID","requestedBy":"ID","requestedAt":"Date","processedAt":"Date","status":"Enum","status_idx":"Integer","reason":"String","firstLessonCompleted":"Boolean","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event tutorban-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-tutorban-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event courseremoval-cascaded **Event topic** : `tutorhub-enrollmentmanagement-service-courseremoval-cascaded` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `enrollments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollments`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollments","method":"POST","action":"list","appVersion":"Version","rowCount":"\"Number\"","enrollments":[{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"Date","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":[]} ``` ## Route Event enrollmentpayment-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayments-listed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayments-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_enrollmentPayments` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayments`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_enrollmentPayments":[{"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 enrollmentpayment-created **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** 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_enrollmentPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-updated **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-deleted **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbyorderid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbyorderid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpaymentbypaymentid-retrived **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpaymentbypaymentid-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_enrollmentPayment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`sys_enrollmentPayment`** object. Note, however, that certain properties might be excluded in accordance with the 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_enrollmentPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_enrollmentPayment":{"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 enrollmentpayment-started **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-refreshed **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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 enrollmentpayment-calledback **Event topic** : `tutorhub-enrollmentmanagement-service-enrollmentpayment-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 `enrollment` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`enrollment`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"enrollment","method":"POST","action":"update","appVersion":"Version","rowCount":1,"enrollment":{"id":"ID","coursePackId":"ID","studentId":"ID","tutorProfileId":"ID","lessonSlotIds":"ID","totalAmount":"Double","currency":"String","paymentStatus":"Enum","paymentStatus_idx":"Integer","refundStatus":"Enum","refundStatus_idx":"Integer","enrollmentStatus":"Enum","enrollmentStatus_idx":"Integer","enrolledAt":"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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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** : `tutorhub-enrollmentmanagement-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 enrollment # Service Design Specification - Object Design for enrollment **tutorhub-enrollmentmanagement-service** documentation ## Document Overview This document outlines the object design for the `enrollment` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## enrollment Data Object ### Object Overview **Description:** Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **enrollment_unique_booking**: [studentId, coursePackId] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Stripe Integration This data object is configured to integrate with Stripe for order management of `enrollment`. It is designed to handle payment processing and order tracking. To manage payments, Mindbricks will design additional Business API routes arround this data object, which will be used checkout orders and charge customers. - **Order Name**: `enrollment` - **Order Id Property**: This MScript expression is used to extract the order's unique identifier from the data object. - **Order Amount Property**: This MScript expression is used to determine the order amount for payment. It should return a numeric value representing the total amount to be charged. - **Order Currency Property**: This MScript expression is used to determine the currency for the order. It should return a string representing the currency code (e.g., "USD", "EUR"). - **Order Description Property**: `Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}` This MScript expression is used to provide a description for the order, which will be shown in Stripe and on customer receipts. It should return a string that describes the order. - **Order Status Property**: paymentStatus This property is selected as the order status property, which will be used to track the current status of the order. It will be automatically updated based on payment results from Stripe. - **Order Status Update Date Property**: updatedAt This property is selected to record the timestamp of the last order status update. It will be automatically managed during payment events to reflect when the status was last changed. - **Order Owner Id Property**: studentId This property is selected as the order owner property, which will be used to track the user who owns the order. It will be used to ensure correct access control in payment flows, allowing only the owner to manage their orders. - **Map Payment Result to Order Status**: This configuration defines how Stripe's payment results (e.g., started, success, failed, canceled) map to internal order statuses., `paymentResultStarted` status will be mapped to a local value using `"pending"` and will be set to `paymentStatus`property. `paymentResultCanceled` status will be mapped to a local value using `"pending"` and will be set to `paymentStatus` property. `paymentResultFailed` status will be mapped to a local value using `"pending"` and will be set to `paymentStatus` property. `paymentResultSuccess` status will be mapped to a local value using `"paid"` and will be set to `paymentStatus` property. - **On Checkout Error**: if an error occurs during the checkout process, the API will continue to execute, allowing for custom error handling. In this case, the payment error will ve recorded as a status update. To make a retry a new checkout, a new order will be created with the same data as the original order. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `coursePackId` | ID | Yes | FK to purchased course pack. | | `studentId` | ID | Yes | FK to enrolling student (auth:user). | | `tutorProfileId` | ID | Yes | FK to the course's tutorProfile for admin/analytics. | | `lessonSlotIds` | ID | Yes | IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). | | `totalAmount` | Double | Yes | Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). | | `currency` | String | Yes | 3-letter ISO currency code (e.g., 'USD', 'EUR'). | | `paymentStatus` | Enum | Yes | Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation). | | `refundStatus` | Enum | Yes | Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. | | `enrollmentStatus` | Enum | Yes | Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated). | | `enrolledAt` | Date | No | Datetime of completed enrollment (post-payment). | | `paymentConfirmation` | Enum | Yes | An automatic property that is used to check the confirmed status of the payment set by webhooks. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Array Properties `lessonSlotIds` Array properties can hold multiple values and are indicated by the `[]` suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **coursePackId**: '00000000-0000-0000-0000-000000000000' - **studentId**: '00000000-0000-0000-0000-000000000000' - **tutorProfileId**: '00000000-0000-0000-0000-000000000000' - **lessonSlotIds**: [] - **totalAmount**: 0.0 - **currency**: USD - **paymentStatus**: pending - **refundStatus**: notRequested - **enrollmentStatus**: pending - **paymentConfirmation**: pending ### Always Create with Default Values Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created. - **paymentStatus**: Will be created with value `pending` - **enrollmentStatus**: Will be created with value `pending` - **paymentConfirmation**: Will be created with value `pending` ### Constant Properties `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` `totalAmount` `currency` `enrolledAt` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `paymentStatus` `refundStatus` `enrollmentStatus` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values. - **paymentStatus**: [pending, paid, refunded] - **refundStatus**: [notRequested, eligible, processed, ineligible] - **enrollmentStatus**: [pending, active, completed, canceled] - **paymentConfirmation**: [pending, processing, paid, canceled] ### Elastic Search Indexing `coursePackId` `studentId` `totalAmount` `currency` `paymentStatus` `refundStatus` `enrollmentStatus` `enrolledAt` `paymentConfirmation` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` `totalAmount` `paymentStatus` `refundStatus` `enrollmentStatus` `paymentConfirmation` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Secondary Key Properties `paymentConfirmation` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Relation Properties `coursePackId` `studentId` `tutorProfileId` `lessonSlotIds` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **studentId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **tutorProfileId**: ID Relation to `tutorProfile`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **lessonSlotIds**: ID Relation to `lessonSlot`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Session Data Properties `studentId` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **studentId**: ID property will be mapped to the session parameter `userId`. This property is also used to store the owner of the session data, allowing for ownership checks and access control. ### Filter Properties `paymentConfirmation` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled. - **paymentConfirmation**: Enum has a filter named `paymentConfirmation` --- ### Service Design Specification - Object Design for refundRequest # Service Design Specification - Object Design for refundRequest **tutorhub-enrollmentmanagement-service** documentation ## Document Overview This document outlines the object design for the `refundRequest` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## refundRequest Data Object ### Object Overview **Description:** A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **unique_enrollment_refund**: [enrollmentId] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `enrollmentId` | ID | Yes | FK to enrollment object for which refund is being requested (unique: one refund per enrollment). | | `requestedBy` | ID | Yes | User (student) making the refund request (auth:user id). | | `requestedAt` | Date | Yes | Datetime refund was requested. | | `processedAt` | Date | No | When refund was processed by system (auto-approval). | | `status` | Enum | Yes | Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). | | `reason` | String | Yes | User-supplied reason for requesting refund. | | `firstLessonCompleted` | Boolean | Yes | True if this refund is after first lesson (enforced by workflow); must be checked before approval. | | `adminNote` | String | No | Admin note explaining the refund decision (approve/reject reason). | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **enrollmentId**: '00000000-0000-0000-0000-000000000000' - **requestedBy**: '00000000-0000-0000-0000-000000000000' - **requestedAt**: new Date() - **status**: pending - **reason**: 'default' - **firstLessonCompleted**: false ### Constant Properties `enrollmentId` `requestedBy` `requestedAt` `reason` `firstLessonCompleted` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `processedAt` `status` `adminNote` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values. - **status**: [pending, approved, rejected, autoApproved] ### Database Indexing `enrollmentId` `requestedBy` `requestedAt` `processedAt` `status` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Unique Properties `enrollmentId` Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option. ### Relation Properties `enrollmentId` `requestedBy` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together. - **enrollmentId**: ID Relation to `enrollment`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes - **requestedBy**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: Yes ### Session Data Properties `requestedBy` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **requestedBy**: ID property will be mapped to the session parameter `userId`. --- ### Service Design Specification - Object Design for sys_enrollmentPayment # Service Design Specification - Object Design for sys_enrollmentPayment **tutorhub-enrollmentmanagement-service** documentation ## Document Overview This document outlines the object design for the `sys_enrollmentPayment` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## sys_enrollmentPayment Data Object ### Object Overview **Description:** A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object's checkout config This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `ownerId` | ID | No | An ID value to represent owner user who created the order | | `orderId` | ID | Yes | an ID value to represent the orderId which is the ID parameter of the source enrollment object | | `paymentId` | String | Yes | A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type | | `paymentStatus` | String | Yes | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | | `statusLiteral` | String | Yes | A string value to represent the logical payment status which belongs to the application lifecycle itself. | | `redirectUrl` | String | No | A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value is set. ### Default Values Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically. - **orderId**: '00000000-0000-0000-0000-000000000000' - **paymentId**: 'default' - **paymentStatus**: 'default' - **statusLiteral**: started ### Constant Properties `orderId` Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object's lifecycle. A property is set to be constant if the `Allow Update` option is set to `false`. ### Auto Update Properties `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` An update crud API created with the option `Auto Params` enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the `Allow Auto Update` option to false. These properties will be added to the update API's body parameters and can be updated by the user if any value is provided in the request body. ### Elastic Search Indexing `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries. ### Database Indexing `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting. ### Unique Properties `orderId` Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the `Indexed in DB` option. ### Secondary Key Properties `orderId` Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key. ### Session Data Properties `ownerId` Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system. - **ownerId**: ID property will be mapped to the session parameter `userId`. This property is also used to store the owner of the session data, allowing for ownership checks and access control. ### Filter Properties `ownerId` `orderId` `paymentId` `paymentStatus` `statusLiteral` `redirectUrl` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's that have "Auto Params" enabled. - **ownerId**: ID has a filter named `ownerId` - **orderId**: ID has a filter named `orderId` - **paymentId**: String has a filter named `paymentId` - **paymentStatus**: String has a filter named `paymentStatus` - **statusLiteral**: String has a filter named `statusLiteral` - **redirectUrl**: String has a filter named `redirectUrl` --- ### Service Design Specification - Object Design for sys_paymentCustomer # Service Design Specification - Object Design for sys_paymentCustomer **tutorhub-enrollmentmanagement-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 **tutorhub-enrollmentmanagement-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 Enrollment` # Business API Design Specification - `Create Enrollment` 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 `createEnrollment` 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 `createEnrollment` Business API is designed to handle a `create` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Creates a new enrollment for a student in a selected course pack and selected lesson slots. Enforces booking prerequisites (availability, non-duplication, preliminary meeting if flagged in coursePack), and triggers Stripe payment. Updates all associated lesson slot statuses to booked. Enrollment remains pending until payment confirmed by Stripe webhook. ## API Frontend Description By The Backend Architect Student chooses course pack, selects lesson slots, triggers enrollment and Stripe payment. If the course requires preliminary screening, checks that it was passed before proceeding. If payment fails, booking is not confirmed. Successful booking sets lesson slots status to 'booked' and opens enrollment. Student, tutor, and admin can see details. ## 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 `enrollment-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 `createEnrollment` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollments` 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 `createEnrollment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createEnrollment` Business API has 9 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `No` | `-` | `body` | `enrollmentId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `coursePackId` | `ID` | `Yes` | `-` | `body` | `coursePackId` | | **Description:** | FK to purchased course pack. | | | | | | | | | | | | | `studentId` | `ID` | `Yes` | `-` | `session` | `userId` | | **Description:** | FK to enrolling student (auth:user). | | | | | | | | | | | | | `tutorProfileId` | `ID` | `Yes` | `-` | `body` | `tutorProfileId` | | **Description:** | FK to the course's tutorProfile for admin/analytics. | | | | | | | | | | | | | `lessonSlotIds` | `ID` | `Yes` | `-` | `body` | `lessonSlotIds` | | **Description:** | IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). | | | | | | | | | | | | | `totalAmount` | `Double` | `Yes` | `-` | `body` | `totalAmount` | | **Description:** | Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). | | | | | | | | | | | | | `currency` | `String` | `Yes` | `-` | `body` | `currency` | | **Description:** | 3-letter ISO currency code (e.g., 'USD', 'EUR'). | | | | | | | | | | | | | `refundStatus` | `Enum` | `Yes` | `-` | `body` | `refundStatus` | | **Description:** | Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. | | | | | | | | | | | | | `enrolledAt` | `Date` | `No` | `-` | `body` | `enrolledAt` | | **Description:** | Datetime of completed enrollment (post-payment). | | | | | | | | | | | | ### 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 `createEnrollment` 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: `[user, student, 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.enrollmentId, coursePackId: this.coursePackId, studentId: this.studentId, tutorProfileId: this.tutorProfileId, lessonSlotIds: this.lessonSlotIds, totalAmount: this.totalAmount, currency: this.currency, refundStatus: this.refundStatus, enrolledAt: this.enrolledAt, 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 : fetchCoursePack **Action Type**: `FetchObjectAction` Fetch the course pack to read scheduling constraints ```js class Api { async fetchCoursePack() { // Fetch Object on childObject coursePack const userQuery = { $and: [ { id: runMScript(() => this.coursePackId, { path: "services[3].businessLogic[0].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("coursePack"); const data = await elasticIndex.getOne(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:coursePack"); } return data; } } ``` --- ### [6] Action : fetchTutorProfile **Action Type**: `FetchObjectAction` Fetch tutor profile to get the tutor's userId for account status check ```js class Api { async fetchTutorProfile() { // Fetch Object on childObject tutorProfile const userQuery = { $and: [ { id: runMScript(() => this.tutorProfileId, { path: "services[3].businessLogic[0].actions.fetchObjectActions[3].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("tutorProfile"); const data = await elasticIndex.getOne(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:tutorProfile"); } return data; } } ``` --- ### [7] Action : fetchTutorUser **Action Type**: `FetchObjectAction` Fetch tutor's auth user record to check accountStatus (active/suspended/banned) ```js class Api { async fetchTutorUser() { // Fetch Object on childObject user const userQuery = { $and: [ { id: runMScript(() => this.fetchedTutorProfile.tutorId, { path: "services[3].businessLogic[0].actions.fetchObjectActions[4].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("user"); const data = await elasticIndex.getOne(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:user"); } return data; } } ``` --- ### [8] Action : fetchScreeningMeetings **Action Type**: `FetchObjectAction` Fetch screening meetings to verify approval status ```js class Api { async fetchScreeningMeetings() { // Fetch Object on childObject preliminaryMeeting const userQuery = { $and: [ runMScript(() => ({ coursePackId: this.coursePackId }), { path: "services[3].businessLogic[0].actions.fetchObjectActions[1].whereClause", }), { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); // get object list from elasticsearch index const elasticIndex = new ElasticIndexer("preliminaryMeeting"); const dataList = (await elasticIndex.getDataByPage(0, 500, scriptQuery)) ?? []; return dataList; } } ``` --- ### [9] Action : fetchEnrolledLessonSlots **Action Type**: `FetchObjectAction` Fetch actual lesson slot records to validate dates/times ```js class Api { async fetchEnrolledLessonSlots() { // Fetch Object on childObject lessonSlot const userQuery = { $and: [ runMScript( () => ({ $and: [ { coursePackId: this.coursePackId }, { studentId: this.session.userId }, ], }), { path: "services[3].businessLogic[0].actions.fetchObjectActions[2].whereClause", }, ), { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); // get object list from elasticsearch index const elasticIndex = new ElasticIndexer("lessonSlot"); const dataList = (await elasticIndex.getDataByPage(0, 500, scriptQuery)) ?? []; return dataList; } } ``` --- ### [10] Action : runEnrollmentValidation **Action Type**: `FunctionCallAction` Run all enrollment constraint validations including tutor status and course moderation checks ```js class Api { async runEnrollmentValidation() { try { return runMScript( () => LIB.validateEnrollmentConstraints( this.fetchedCoursePack, this.lessonSlotIds, this.screeningMeetings, this.session.userId, this.tutorUser, ), { path: "services[3].businessLogic[0].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error( "Error in FunctionCallAction runEnrollmentValidation:", err, ); throw err; } } } ``` --- ### [11] Action : enforceEnrollmentConstraints **Action Type**: `ValidationAction` Block enrollment if any constraint is violated ```js class Api { async enforceEnrollmentConstraints() { const isValid = runMScript( () => this.enrollmentValidation && this.enrollmentValidation.valid === true, { path: "services[3].businessLogic[0].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError( "Enrollment validation failed. Please check course pack, lesson slots, and screening requirements.", ); } return isValid; } } ``` --- ### [12] 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` --- ### [13] 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` --- ### [14] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [15] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [16] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [17] 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 `createEnrollment` api has got 7 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | lessonSlotIds | ID | true | request.body?.["lessonSlotIds"] | | totalAmount | Double | true | request.body?.["totalAmount"] | | currency | String | true | request.body?.["currency"] | | refundStatus | Enum | true | request.body?.["refundStatus"] | | enrolledAt | Date | false | request.body?.["enrolledAt"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/enrollments** ```js axios({ method: 'POST', url: '/v1/enrollments', data: { coursePackId:"ID", tutorProfileId:"ID", lessonSlotIds:"ID", totalAmount:"Double", currency:"String", refundStatus:"Enum", enrolledAt:"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 **`enrollment`** 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": "enrollment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Enrollment` # Business API Design Specification - `Get Enrollment` 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 `getEnrollment` 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 `getEnrollment` Business API is designed to handle a `get` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Fetch a single enrollment, including all details and linked objects (student, coursePack, lessonSlots). Only the enrollment's student, tutor, or admin may view. ## API Frontend Description By The Backend Architect Enrollment owners (student), relevant tutor, and admin can see all details of an enrollment via this API. Contains lesson slot list, linked pack, payment/refund status, fulfillment states for transparency. ## 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 `getEnrollment` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollments/:enrollmentId` 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 `getEnrollment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getEnrollment` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `Yes` | `-` | `urlpath` | `enrollmentId` | | **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 `getEnrollment` 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: `[user, student, tutor, 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.", `id`,`coursePackId`,`studentId`,`tutorProfileId`,`lessonSlotIds`,`totalAmount`,`currency`,`paymentStatus`,`refundStatus`,`enrollmentStatus`,`enrolledAt` ## 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.enrollmentId},{isActive:true}]}), {"path":"services[3].businessLogic[1].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 `getEnrollment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/enrollments/:enrollmentId** ```js axios({ method: 'GET', url: `/v1/enrollments/${enrollmentId}`, 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 **`enrollment`** 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": "enrollment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "enrollment": { "coursePack": { "tutorProfileId": "ID", "title": "String", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer" }, "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String" }, {}, {} ], "student": { "fullname": "String", "avatar": "String" }, "tutorProfile": { "tutorId": "ID", "certifications": "String", "bio": "Text", "profilePhoto": "String" }, "isActive": true } } ``` --- ### Business API Design Specification - `List Enrollments` # Business API Design Specification - `List Enrollments` 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 `listEnrollments` 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 `listEnrollments` Business API is designed to handle a `list` operation on the `Enrollment` 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 enrollments. Admin sees all; students see their enrollments; tutors see enrollments where their tutorProfileId matches. ## API Frontend Description By The Backend Architect Admins see all enrollments; students see their own; tutors can filter enrollments to their packs by tutorProfileId. Response is enriched with embedded course, lesson, and user details as requested by the frontend. ## 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 `listEnrollments` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollments` 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 `listEnrollments` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listEnrollments` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `No` | `` | `query` | `tutorProfileId` | | **Description:** | Optional tutor profile ID filter for tutors to see enrollments in their courses. | | | | | | | | | | | | ### Filter Parameters The `listEnrollments` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `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/enrollments?paymentConfirmation=active // Get records with multiple enum values (use multiple parameters) GET /v1/enrollments?paymentConfirmation=active&paymentConfirmation=pending // Get records without this field GET /v1/enrollments?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 `listEnrollments` 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: `[user, student, tutor, 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 (()=>{ if(this.session.roleId==="admin"||this.session.roleId==="superAdmin"){return {id:{$ne:"00000000-0000-0000-0000-000000000000"}};} if(this.tutorProfileId){ return {'$or':[{studentId:this.session.userId},{tutorProfileId:this.tutorProfileId}]}; } return {studentId: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:[(()=>{ if(this.session.roleId==="admin"||this.session.roleId==="superAdmin"){return {id:{$ne:"00000000-0000-0000-0000-000000000000"}};} if(this.tutorProfileId){ return {'$or':[{studentId:this.session.userId},{tutorProfileId:this.tutorProfileId}]}; } return {studentId:this.session.userId}; })(),{isActive:true}]}), {"path":"services[3].businessLogic[2].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 `listEnrollments` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | false | request.query?.["tutorProfileId"] | The `listEnrollments` 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | 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/enrollments** ```js axios({ method: 'GET', url: '/v1/enrollments', data: { }, params: { tutorProfileId:'"ID"', // Filter parameters (see Filter Parameters section for usage examples) // 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 **`enrollments`** 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": "enrollments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "coursePack": [ { "title": "String", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "isActive": true }, {}, {} ], "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer" }, {}, {} ], "student": [ { "email": "String", "fullname": "String", "avatar": "String" }, {}, {} ], "tutorProfile": [ { "tutorId": "ID", "bio": "Text" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Refundrequest` # Business API Design Specification - `Create Refundrequest` 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 `createRefundRequest` 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 `createRefundRequest` Business API is designed to handle a `create` operation on the `RefundRequest` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Student files refund request for a completed enrollment only after first lesson and only if no additional lessons are complete. Auto-approves, updates enrollment statuses, and triggers Stripe refund if eligible. ## API Frontend Description By The Backend Architect Students can trigger a refund for their enrollment only after first lesson, provided no additional lessons have been completed. The refund is auto-approved and reflected in both user's and admin's views; tutor and admin are notified. No manual approval or asynchronous queue, strictly within narrow business criteria. ## 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 `refundrequest-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 `createRefundRequest` Business API includes a REST controller that can be triggered via the following route: `/v1/refundrequests` 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 `createRefundRequest` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createRefundRequest` Business API has 9 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `refundRequestId` | `ID` | `No` | `-` | `body` | `refundRequestId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `enrollmentId` | `ID` | `Yes` | `-` | `body` | `enrollmentId` | | **Description:** | FK to enrollment object for which refund is being requested (unique: one refund per enrollment). | | | | | | | | | | | | | `requestedBy` | `ID` | `Yes` | `-` | `session` | `userId` | | **Description:** | User (student) making the refund request (auth:user id). | | | | | | | | | | | | | `requestedAt` | `Date` | `Yes` | `-` | `body` | `requestedAt` | | **Description:** | Datetime refund was requested. | | | | | | | | | | | | | `processedAt` | `Date` | `No` | `-` | `body` | `processedAt` | | **Description:** | When refund was processed by system (auto-approval). | | | | | | | | | | | | | `status` | `Enum` | `Yes` | `-` | `body` | `status` | | **Description:** | Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). | | | | | | | | | | | | | `reason` | `String` | `Yes` | `-` | `body` | `reason` | | **Description:** | User-supplied reason for requesting refund. | | | | | | | | | | | | | `firstLessonCompleted` | `Boolean` | `Yes` | `-` | `body` | `firstLessonCompleted` | | **Description:** | True if this refund is after first lesson (enforced by workflow); must be checked before approval. | | | | | | | | | | | | | `adminNote` | `String` | `No` | `-` | `body` | `adminNote` | | **Description:** | Admin note explaining the refund decision (approve/reject reason). | | | | | | | | | | | | ### 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 `createRefundRequest` 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: `[user, student, 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.refundRequestId, enrollmentId: this.enrollmentId, requestedBy: this.requestedBy, requestedAt: this.requestedAt, processedAt: this.processedAt, status: this.status, reason: this.reason, firstLessonCompleted: this.firstLessonCompleted, adminNote: this.adminNote, 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 : fetchEnrollment **Action Type**: `FetchObjectAction` Fetch the enrollment record to validate payment status and refund eligibility ```js class Api { async fetchEnrollment() { // Fetch Object on childObject enrollment const userQuery = { $and: [ { id: runMScript(() => this.enrollmentId, { path: "services[3].businessLogic[3].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getEnrollmentByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:enrollment"); } return data; } } ``` --- ### [6] Action : fetchPaymentRecord **Action Type**: `FetchObjectAction` Fetch the Stripe payment record to get paymentId for refund ```js class Api { async fetchPaymentRecord() { // Fetch Object on childObject sys_enrollmentPayment const userQuery = { $and: [ { orderId: runMScript(() => this.enrollmentId, { path: "services[3].businessLogic[3].actions.fetchObjectActions[1].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getSys_enrollmentPaymentByQuery(scriptQuery); if (!data) { throw new NotFoundError( "errMsg_FethcedObjectNotFound:sys_enrollmentPayment", ); } return data; } } ``` --- ### [7] Action : fetchLessonSlots **Action Type**: `FetchObjectAction` Fetch all lesson slots for this enrollment to check completion status ```js class Api { async fetchLessonSlots() { // Fetch Object on childObject lessonSlot const userQuery = { $and: [ runMScript( () => ({ id: { $in: this.fetchedEnrollment.lessonSlotIds } }), { path: "services[3].businessLogic[3].actions.fetchObjectActions[2].whereClause", }, ), { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); // get object list from elasticsearch index const elasticIndex = new ElasticIndexer("lessonSlot"); const dataList = (await elasticIndex.getDataByPage(0, 500, scriptQuery)) ?? []; return dataList; } } ``` --- ### [8] Action : runRefundValidation **Action Type**: `FunctionCallAction` Validate refund eligibility based on enrollment status, payment, and lesson completion ```js class Api { async runRefundValidation() { try { return runMScript( () => LIB.validateRefundEligibility( this.fetchedEnrollment, this.enrollmentLessonSlots, this.paymentRecord, ), { path: "services[3].businessLogic[3].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction runRefundValidation:", err); throw err; } } } ``` --- ### [9] Action : enforceRefundEligibility **Action Type**: `ValidationAction` Block refund if eligibility validation fails ```js class Api { async enforceRefundEligibility() { const isValid = runMScript( () => this.refundValidation && this.refundValidation.eligible === true, { path: "services[3].businessLogic[3].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError( "Refund not eligible. Please check the refund policy requirements.", ); } return isValid; } } ``` --- ### [10] Action : setRefundFields **Action Type**: `AddToContextAction` Set auto-computed fields: autoApproved gets instant processing, pendingReview gets pending status ```js class Api { async setRefundFields() { try { this["firstLessonCompleted"] = runMScript( () => this.refundValidation.firstLessonCompleted || false, { path: "services[3].businessLogic[3].actions.addToContextActions[0].context[0].contextValue", }, ); this["status"] = runMScript( () => this.refundValidation.refundType === "autoApproved" ? "autoApproved" : "pending", { path: "services[3].businessLogic[3].actions.addToContextActions[0].context[1].contextValue", }, ); this["processedAt"] = runMScript( () => this.refundValidation.refundType === "autoApproved" ? new Date() : null, { path: "services[3].businessLogic[3].actions.addToContextActions[0].context[2].contextValue", }, ); this["requestedAt"] = runMScript(() => new Date(), { path: "services[3].businessLogic[3].actions.addToContextActions[0].context[3].contextValue", }); return true; } catch (error) { console.error("AddToContextAction error:", error); throw error; } } } ``` --- ### [11] 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` --- ### [12] 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` --- ### [13] Step : mainCreateOperation Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records. --- ### [14] Action : stripeCreateRefund **Action Type**: `IntegrationAction` Process the actual Stripe refund — only for auto-approved refunds ```js class Api { async stripeCreateRefund() { // Integration Action for stripe const input = { paymentIntent: runMScript( () => this.refundValidation.stripePaymentIntentId, { path: "services[3].businessLogic[3].actions.integrationActions[0].parameters[0].parameterValue", }, ), reason: runMScript(() => "requested_by_customer", { path: "services[3].businessLogic[3].actions.integrationActions[0].parameters[1].parameterValue", }), }; const stripeClient = await getIntegrationClient("stripe"); return await stripeClient.createRefund(input); } } ``` --- ### [15] Action : updateEnrollmentRefundStatus **Action Type**: `UpdateCrudAction` Mark the enrollment as refunded — only for auto-approved refunds ```js class Api { async updateEnrollmentRefundStatus() { // Aggregated Update Operation on childObject enrollment const params = { refundStatus: runMScript(() => "processed", { path: "services[3].businessLogic[3].actions.updateCrudActions[0].dataClause[0].dataValue", }), paymentStatus: runMScript(() => "refunded", { path: "services[3].businessLogic[3].actions.updateCrudActions[0].dataClause[1].dataValue", }), enrollmentStatus: runMScript(() => "canceled", { path: "services[3].businessLogic[3].actions.updateCrudActions[0].dataClause[2].dataValue", }), }; const userQuery = runMScript(() => ({ id: this.enrollmentId }), { path: "services[3].businessLogic[3].actions.updateCrudActions[0].whereClause", }); const { convertUserQueryToSequelizeQuery } = require("common"); const query = convertUserQueryToSequelizeQuery(userQuery); const result = await updateEnrollmentByQuery(params, query, this); if (!result) return null; const resultArray = Array.isArray(result) ? result : [result]; // if updated record is in main data update main data if (this.dbResult) { for (const item of resultArray) { if (item.id == this.dbResult.id) { Object.assign(this.dbResult, item); this.refundRequest = this.dbResult; } } } if (resultArray.length == 0) return null; if (resultArray.length == 1) return resultArray[0]; return resultArray; } } ``` --- ### [16] Action : freeLessonSlots **Action Type**: `FunctionCallAction` Cancel lesson slots when refund is auto-approved ```js class Api { async freeLessonSlots() { try { return await runMScript( () => (async () => await LIB.cancelEnrollmentLessonSlots( this.fetchedEnrollment.lessonSlotIds, this.session, ))(), { path: "services[3].businessLogic[3].actions.functionCallActions[1].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction freeLessonSlots:", err); throw err; } } } ``` --- ### [17] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [18] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [19] 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 `createRefundRequest` api has got 7 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.body?.["enrollmentId"] | | requestedAt | Date | true | request.body?.["requestedAt"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | true | request.body?.["status"] | | reason | String | true | request.body?.["reason"] | | firstLessonCompleted | Boolean | true | request.body?.["firstLessonCompleted"] | | adminNote | String | false | request.body?.["adminNote"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/refundrequests** ```js axios({ method: 'POST', url: '/v1/refundrequests', data: { enrollmentId:"ID", requestedAt:"Date", processedAt:"Date", status:"Enum", reason:"String", firstLessonCompleted:"Boolean", adminNote:"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 **`refundRequest`** 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": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Refundrequest` # Business API Design Specification - `Get Refundrequest` 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 `getRefundRequest` 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 `getRefundRequest` Business API is designed to handle a `get` operation on the `RefundRequest` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get refund request record for audit—visible to student (their own), tutor (if their course), or admin. Linked enrollment, user, and status are included. ## API Frontend Description By The Backend Architect Students check status of their refund request; tutors may audit if linked to their courses; admins can view all. Details include enrollment and state for auditing. ## 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 `getRefundRequest` Business API includes a REST controller that can be triggered via the following route: `/v1/refundrequests/:refundRequestId` 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 `getRefundRequest` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getRefundRequest` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `refundRequestId` | `ID` | `Yes` | `-` | `urlpath` | `refundRequestId` | | **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 `getRefundRequest` 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: `[user, student, tutor, 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.", `id`,`enrollmentId`,`requestedBy`,`requestedAt`,`processedAt`,`status`,`reason`,`firstLessonCompleted` ## 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.refundRequestId},{isActive:true}]}), {"path":"services[3].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 `getRefundRequest` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/refundrequests/:refundRequestId** ```js axios({ method: 'GET', url: `/v1/refundrequests/${refundRequestId}`, 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 **`refundRequest`** 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": "refundRequest", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "refundRequest": { "enrollment": { "coursePackId": "ID", "studentId": "ID" }, "isActive": true } } ``` --- ### Business API Design Specification - `List Refundrequests` # Business API Design Specification - `List Refundrequests` 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 `listRefundRequests` 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 `listRefundRequests` Business API is designed to handle a `list` operation on the `RefundRequest` 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 refund requests (students see their own, admins see all, tutors see linked to their courses via coursePack). ## API Frontend Description By The Backend Architect Admins list all refund requests; students see their submitted refunds; tutors see those linked to their courses for reporting and audit. Each item shows enrollment link and high-level audit fields. ## 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 `listRefundRequests` Business API includes a REST controller that can be triggered via the following route: `/v1/refundrequests` 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 `listRefundRequests` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listRefundRequests` 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 `listRefundRequests` 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: `[user, student, tutor, 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.", `id`,`enrollmentId`,`requestedBy`,`requestedAt`,`processedAt`,`status`,`reason`,`adminNote`,`firstLessonCompleted` ## 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 (()=>{ if(this.session.roleId==="admin"||this.session.roleId==="superAdmin"){return {id:{$ne:"00000000-0000-0000-0000-000000000000"}}}; if(this.session.roleId==="student"){return {requestedBy: this.session.userId}}; if(this.session.roleId==="tutor"){return {id:{$ne:"00000000-0000-0000-0000-000000000000"}}}; return {id:null} })() ``` **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:[(()=>{ if(this.session.roleId==="admin"||this.session.roleId==="superAdmin"){return {id:{$ne:"00000000-0000-0000-0000-000000000000"}}}; if(this.session.roleId==="student"){return {requestedBy: this.session.userId}}; if(this.session.roleId==="tutor"){return {id:{$ne:"00000000-0000-0000-0000-000000000000"}}}; return {id:null} })(),{isActive:true}]}), {"path":"services[3].businessLogic[5].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 `listRefundRequests` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/refundrequests** ```js axios({ method: 'GET', url: '/v1/refundrequests', 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 **`refundRequests`** 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": "refundRequests", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "refundRequests": [ { "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "totalAmount": "Double", "currency": "String" }, {}, {} ], "coursePack": { "title": "String" }, "requester": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Update Refundrequest` # Business API Design Specification - `Update Refundrequest` 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 `updateRefundRequest` 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 `updateRefundRequest` Business API is designed to handle a `update` operation on the `RefundRequest` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin updates a refund request: approve or reject with an admin note. Only admins can update refund requests. ## API Frontend Description By The Backend Architect Admin-only endpoint for processing pending refund requests. Admin sets status to approved or rejected and optionally provides an adminNote explaining the decision. processedAt is set automatically on approval/rejection. ## 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 `updateRefundRequest` Business API includes a REST controller that can be triggered via the following route: `/v1/refundrequests/:refundRequestId` 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 `updateRefundRequest` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateRefundRequest` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `refundRequestId` | `ID` | `Yes` | `-` | `urlpath` | `refundRequestId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `processedAt` | `Date` | `No` | `-` | `body` | `processedAt` | | **Description:** | When refund was processed by system (auto-approval). | | | | | | | | | | | | | `status` | `Enum` | `No` | `-` | `body` | `status` | | **Description:** | Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). | | | | | | | | | | | | | `adminNote` | `String` | `No` | `-` | `body` | `adminNote` | | **Description:** | Admin note explaining the refund decision (approve/reject reason). | | | | | | | | | | | | ### 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 `updateRefundRequest` 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]` --- ## 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.refundRequestId},{isActive:true}]}), {"path":"services[3].businessLogic[6].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 { processedAt: this.processedAt, status: this.status, adminNote: this.adminNote, } ``` ## 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 `updateRefundRequest` api has got 4 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/refundrequests/:refundRequestId** ```js axios({ method: 'PATCH', url: `/v1/refundrequests/${refundRequestId}`, data: { processedAt:"Date", status:"Enum", adminNote:"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 **`refundRequest`** 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": "refundRequest", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Cancel Enrollment` # Business API Design Specification - `Cancel Enrollment` 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 `cancelEnrollment` 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 `cancelEnrollment` Business API is designed to handle a `update` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin force-cancels an enrollment. Sets enrollmentStatus to canceled, paymentStatus to refunded, refundStatus to processed. Used when a tutor is banned/suspended or a course is removed. ## API Frontend Description By The Backend Architect Admin-only action to force-cancel an enrollment. Used when tutor is banned, suspended, or course is removed. ## 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 `enrollment-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 `cancelEnrollment` Business API includes a REST controller that can be triggered via the following route: `/v1/cancelenrollment/:enrollmentId` 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 `cancelEnrollment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `cancelEnrollment` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `Yes` | `-` | `urlpath` | `enrollmentId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `cancelReason` | `String` | `No` | `-` | `body` | `cancelReason` | | **Description:** | Admin reason for canceling the enrollment | | | | | | | | | | | | ### 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 `cancelEnrollment` 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]` --- ## 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.enrollmentId},{isActive:true}]}), {"path":"services[3].businessLogic[7].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 {} ``` ## 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 : validateCancelable **Action Type**: `ValidationAction` Ensure enrollment is not already canceled ```js class Api { async validateCancelable() { const isValid = runMScript( () => this.dbInstance && this.dbInstance.enrollmentStatus !== "canceled", { path: "services[3].businessLogic[7].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError("This enrollment is already canceled."); } return isValid; } } ``` --- ### [10] Action : setCancelFields **Action Type**: `AddToContextAction` Set enrollment fields to canceled/refunded/processed for the main update operation ```js class Api { async setCancelFields() { try { this["enrollmentStatus"] = runMScript(() => "canceled", { path: "services[3].businessLogic[7].actions.addToContextActions[0].context[0].contextValue", }); this["paymentStatus"] = runMScript(() => "refunded", { path: "services[3].businessLogic[7].actions.addToContextActions[0].context[1].contextValue", }); this["refundStatus"] = runMScript(() => "processed", { path: "services[3].businessLogic[7].actions.addToContextActions[0].context[2].contextValue", }); return true; } catch (error) { console.error("AddToContextAction error:", error); throw error; } } } ``` --- ### [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] Action : freeLessonSlots **Action Type**: `FunctionCallAction` Cancel all lesson slots associated with this enrollment ```js class Api { async freeLessonSlots() { try { return await runMScript( () => (async () => await LIB.cancelEnrollmentLessonSlots( this.dbInstance.lessonSlotIds, this.session, ))(), { path: "services[3].businessLogic[7].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction freeLessonSlots:", err); throw err; } } } ``` --- ### [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 `cancelEnrollment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | cancelReason | String | | request.body?.["cancelReason"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/cancelenrollment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/cancelenrollment/${enrollmentId}`, data: { cancelReason:"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 **`enrollment`** 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Admin Refundenrollment` # Business API Design Specification - `Admin Refundenrollment` 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 `adminRefundEnrollment` 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 `adminRefundEnrollment` Business API is designed to handle a `create` operation on the `RefundRequest` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin-initiated refund for an enrollment. Creates a refundRequest with autoApproved status, cancels the enrollment, and triggers Stripe refund. No student eligibility checks — admin override. ## API Frontend Description By The Backend Architect Admin-only action to refund an enrollment on behalf of a student. Used when tutor is banned/suspended, course removed, or admin decides a refund is warranted. The enrollment is immediately canceled and a refund request record is created for audit. ## 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 `refundenrollment-admined` 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 `adminRefundEnrollment` Business API includes a REST controller that can be triggered via the following route: `/v1/adminrefundenrollment` 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 `adminRefundEnrollment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `adminRefundEnrollment` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `refundRequestId` | `ID` | `No` | `-` | `body` | `refundRequestId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `enrollmentId` | `ID` | `No` | `-` | `body` | `enrollmentId` | | **Description:** | The enrollment to refund | | | | | | | | | | | | | `reason` | `String` | `No` | `-` | `body` | `reason` | | **Description:** | Admin reason for issuing the refund | | | | | | | | | | | | ### 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 `adminRefundEnrollment` 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** *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.refundRequestId, enrollmentId: this.enrollmentId, requestedBy: this.requestedBy, requestedAt: this.requestedAt, processedAt: this.processedAt, status: this.status, reason: this.reason, firstLessonCompleted: this.firstLessonCompleted, adminNote: this.adminNote, 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 : fetchEnrollment **Action Type**: `FetchObjectAction` Fetch the enrollment to validate and get payment info ```js class Api { async fetchEnrollment() { // Fetch Object on childObject enrollment const userQuery = { $and: [ { id: runMScript(() => this.enrollmentId, { path: "services[3].businessLogic[8].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getEnrollmentByQuery(scriptQuery); if (!data) { throw new NotFoundError("errMsg_FethcedObjectNotFound:enrollment"); } return data; } } ``` --- ### [6] Action : fetchPaymentRecord **Action Type**: `FetchObjectAction` Fetch Stripe payment record for refund processing ```js class Api { async fetchPaymentRecord() { // Fetch Object on childObject sys_enrollmentPayment const userQuery = { $and: [ { orderId: runMScript(() => this.enrollmentId, { path: "services[3].businessLogic[8].actions.fetchObjectActions[1].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToSequelizeQuery } = require("common"); const scriptQuery = convertUserQueryToSequelizeQuery(userQuery); // get object from db const data = await getSys_enrollmentPaymentByQuery(scriptQuery); return data; } } ``` --- ### [7] Action : validateRefundable **Action Type**: `ValidationAction` Ensure enrollment is not already canceled/refunded ```js class Api { async validateRefundable() { const isValid = runMScript( () => this.fetchedEnrollment && this.fetchedEnrollment.enrollmentStatus !== "canceled" && this.fetchedEnrollment.refundStatus !== "processed", { path: "services[3].businessLogic[8].actions.validationActions[0].validationScript", }, ); if (!isValid) { throw new BadRequestError( "This enrollment is already canceled or refunded.", ); } return isValid; } } ``` --- ### [8] Action : setAdminRefundFields **Action Type**: `AddToContextAction` Set refund request fields for admin-initiated refund ```js class Api { async setAdminRefundFields() { try { this["requestedBy"] = runMScript(() => this.session.userId, { path: "services[3].businessLogic[8].actions.addToContextActions[0].context[0].contextValue", }); this["requestedAt"] = runMScript(() => new Date(), { path: "services[3].businessLogic[8].actions.addToContextActions[0].context[1].contextValue", }); this["processedAt"] = runMScript(() => new Date(), { path: "services[3].businessLogic[8].actions.addToContextActions[0].context[2].contextValue", }); this["status"] = runMScript(() => "autoApproved", { path: "services[3].businessLogic[8].actions.addToContextActions[0].context[3].contextValue", }); this["firstLessonCompleted"] = runMScript(() => false, { path: "services[3].businessLogic[8].actions.addToContextActions[0].context[4].contextValue", }); this["adminNote"] = runMScript(() => this.reason, { path: "services[3].businessLogic[8].actions.addToContextActions[0].context[5].contextValue", }); return true; } catch (error) { console.error("AddToContextAction error:", error); throw error; } } } ``` --- ### [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] Action : stripeAdminRefund **Action Type**: `IntegrationAction` Process Stripe refund for admin-initiated refund ```js class Api { async stripeAdminRefund() { // Integration Action for stripe const input = { paymentIntent: runMScript( () => this.paymentRecord && this.paymentRecord.paymentId, { path: "services[3].businessLogic[8].actions.integrationActions[0].parameters[0].parameterValue", }, ), reason: runMScript(() => "requested_by_customer", { path: "services[3].businessLogic[8].actions.integrationActions[0].parameters[1].parameterValue", }), }; const stripeClient = await getIntegrationClient("stripe"); return await stripeClient.createRefund(input); } } ``` --- ### [13] Action : cancelEnrollmentAfterRefund **Action Type**: `UpdateCrudAction` Cancel the enrollment after admin refund ```js class Api { async cancelEnrollmentAfterRefund() { // Aggregated Update Operation on childObject enrollment const params = { enrollmentStatus: runMScript(() => "canceled", { path: "services[3].businessLogic[8].actions.updateCrudActions[0].dataClause[0].dataValue", }), paymentStatus: runMScript(() => "refunded", { path: "services[3].businessLogic[8].actions.updateCrudActions[0].dataClause[1].dataValue", }), refundStatus: runMScript(() => "processed", { path: "services[3].businessLogic[8].actions.updateCrudActions[0].dataClause[2].dataValue", }), }; const userQuery = runMScript(() => ({ id: this.enrollmentId }), { path: "services[3].businessLogic[8].actions.updateCrudActions[0].whereClause", }); const { convertUserQueryToSequelizeQuery } = require("common"); const query = convertUserQueryToSequelizeQuery(userQuery); const result = await updateEnrollmentByQuery(params, query, this); if (!result) return null; const resultArray = Array.isArray(result) ? result : [result]; // if updated record is in main data update main data if (this.dbResult) { for (const item of resultArray) { if (item.id == this.dbResult.id) { Object.assign(this.dbResult, item); this.refundRequest = this.dbResult; } } } if (resultArray.length == 0) return null; if (resultArray.length == 1) return resultArray[0]; return resultArray; } } ``` --- ### [14] Action : freeLessonSlots **Action Type**: `FunctionCallAction` Cancel all lesson slots associated with this enrollment ```js class Api { async freeLessonSlots() { try { return await runMScript( () => (async () => await LIB.cancelEnrollmentLessonSlots( this.fetchedEnrollment.lessonSlotIds, this.session, ))(), { path: "services[3].businessLogic[8].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction freeLessonSlots:", err); throw err; } } } ``` --- ### [15] Step : buildOutput Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract. --- ### [16] Step : sendResponse Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state. --- ### [17] 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 `adminRefundEnrollment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | | reason | String | | request.body?.["reason"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/adminrefundenrollment** ```js axios({ method: 'POST', url: '/v1/adminrefundenrollment', data: { enrollmentId:"ID", reason:"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 **`refundRequest`** 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": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Cascade Tutorban` # Business API Design Specification - `Cascade Tutorban` 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 `cascadeTutorBan` 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 `cascadeTutorBan` Business API is designed to handle a `list` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin cascade: cancel all active enrollments for a banned/suspended tutor. ## API Frontend Description By The Backend Architect Called after admin bans or suspends a tutor. Cancels all active enrollments and frees slots. ## 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 `tutorban-cascaded` 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 `cascadeTutorBan` Business API includes a REST controller that can be triggered via the following route: `/v1/cascadetutorban` 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 `cascadeTutorBan` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `cascadeTutorBan` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `tutorProfileId` | `ID` | `No` | `-` | `body` | `tutorProfileId` | | **Description:** | The tutor profile whose enrollments should be canceled | | | | | | | | | | | | | `reason` | `String` | `No` | `-` | `body` | `reason` | | **Description:** | Reason for cascade cancellation | | | | | | | | | | | | ### Filter Parameters The `cascadeTutorBan` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `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/cascadetutorban?paymentConfirmation=active // Get records with multiple enum values (use multiple parameters) GET /v1/cascadetutorban?paymentConfirmation=active&paymentConfirmation=pending // Get records without this field GET /v1/cascadetutorban?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 `cascadeTutorBan` 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}), {"path":"services[3].businessLogic[9].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] Action : runCascadeCancel **Action Type**: `FunctionCallAction` Cancel all active enrollments for the specified tutor ```js class Api { async runCascadeCancel() { try { return await runMScript( () => (async () => await LIB.cancelAllTutorEnrollments( this.tutorProfileId, this.reason, this.session, ))(), { path: "services[3].businessLogic[9].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction runCascadeCancel:", err); throw err; } } } ``` --- ### [6] 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` --- ### [7] 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` --- ### [8] 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` --- ### [9] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [10] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [11] 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 `cascadeTutorBan` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | reason | String | | request.body?.["reason"] | The `cascadeTutorBan` 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | 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 **POST /v1/cascadetutorban** ```js axios({ method: 'POST', url: '/v1/cascadetutorban', data: { tutorProfileId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section for usage examples) // 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 **`enrollments`** 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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 - `Cascade Courseremoval` # Business API Design Specification - `Cascade Courseremoval` 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 `cascadeCourseRemoval` 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 `cascadeCourseRemoval` Business API is designed to handle a `list` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin cascade: cancel all active enrollments for a removed course pack. ## API Frontend Description By The Backend Architect Called after admin removes a course. Cancels all active enrollments and frees slots. ## 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 `courseremoval-cascaded` 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 `cascadeCourseRemoval` Business API includes a REST controller that can be triggered via the following route: `/v1/cascadecourseremoval` 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 `cascadeCourseRemoval` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `cascadeCourseRemoval` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `coursePackId` | `ID` | `No` | `-` | `body` | `coursePackId` | | **Description:** | The course pack whose enrollments should be canceled | | | | | | | | | | | | | `reason` | `String` | `No` | `-` | `body` | `reason` | | **Description:** | Reason for cascade cancellation | | | | | | | | | | | | ### Filter Parameters The `cascadeCourseRemoval` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `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/cascadecourseremoval?paymentConfirmation=active // Get records with multiple enum values (use multiple parameters) GET /v1/cascadecourseremoval?paymentConfirmation=active&paymentConfirmation=pending // Get records without this field GET /v1/cascadecourseremoval?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 `cascadeCourseRemoval` 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}), {"path":"services[3].businessLogic[10].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] Action : runCascadeCancel **Action Type**: `FunctionCallAction` Cancel all active enrollments for the specified course ```js class Api { async runCascadeCancel() { try { return await runMScript( () => (async () => await LIB.cancelAllCourseEnrollments( this.coursePackId, this.reason, this.session, ))(), { path: "services[3].businessLogic[10].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction runCascadeCancel:", err); throw err; } } } ``` --- ### [6] 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` --- ### [7] 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` --- ### [8] 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` --- ### [9] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [10] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [11] 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 `cascadeCourseRemoval` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | | request.body?.["coursePackId"] | | reason | String | | request.body?.["reason"] | The `cascadeCourseRemoval` 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | 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 **POST /v1/cascadecourseremoval** ```js axios({ method: 'POST', url: '/v1/cascadecourseremoval', data: { coursePackId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section for usage examples) // 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 **`enrollments`** 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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 - `Cleanup Pendingenrollments` # Business API Design Specification - `Cleanup Pendingenrollments` 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 `cleanupPendingEnrollments` 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 `cleanupPendingEnrollments` Business API is designed to handle a `list` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Cleanup stale pending enrollments that were never paid. Cancels them and frees lesson slots. Default timeout: 60 minutes. ## API Frontend Description By The Backend Architect Admin or system cron calls this to clean up abandoned enrollments. Can also be triggered from frontend as a housekeeping action. ## 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 `cleanupPendingEnrollments` Business API includes a REST controller that can be triggered via the following route: `/v1/cleanuppendingenrollments` 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 `cleanupPendingEnrollments` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `cleanupPendingEnrollments` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `maxAgeMinutes` | `Integer` | `No` | `-` | `body` | `maxAgeMinutes` | | **Description:** | How old (in minutes) a pending enrollment must be to get cleaned up. Default: 60 | | | | | | | | | | | | ### Filter Parameters The `cleanupPendingEnrollments` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `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/cleanuppendingenrollments?paymentConfirmation=active // Get records with multiple enum values (use multiple parameters) GET /v1/cleanuppendingenrollments?paymentConfirmation=active&paymentConfirmation=pending // Get records without this field GET /v1/cleanuppendingenrollments?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 `cleanupPendingEnrollments` 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}), {"path":"services[3].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] Action : runCleanup **Action Type**: `FunctionCallAction` Clean up stale pending enrollments ```js class Api { async runCleanup() { try { return await runMScript( () => (async () => await LIB.cleanupPendingEnrollments( this.maxAgeMinutes || 60, this.session, ))(), { path: "services[3].businessLogic[11].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction runCleanup:", err); throw err; } } } ``` --- ### [6] 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` --- ### [7] 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` --- ### [8] 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` --- ### [9] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [10] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [11] 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 `cleanupPendingEnrollments` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | maxAgeMinutes | Integer | | request.body?.["maxAgeMinutes"] | The `cleanupPendingEnrollments` 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | 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 **POST /v1/cleanuppendingenrollments** ```js axios({ method: 'POST', url: '/v1/cleanuppendingenrollments', data: { maxAgeMinutes:"Integer", }, params: { // Filter parameters (see Filter Parameters section for usage examples) // 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 **`enrollments`** 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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 - `Check Enrollmentcompletion` # Business API Design Specification - `Check Enrollmentcompletion` 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 `checkEnrollmentCompletion` 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 `checkEnrollmentCompletion` Business API is designed to handle a `list` operation on the `Enrollment` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Check if all lesson slots in an enrollment are completed and mark enrollment as completed if so. ## API Frontend Description By The Backend Architect Called after a lesson is marked completed. Checks if all lessons are done and auto-completes the enrollment. ## 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 `checkEnrollmentCompletion` Business API includes a REST controller that can be triggered via the following route: `/v1/checkenrollmentcompletion` 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 `checkEnrollmentCompletion` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `checkEnrollmentCompletion` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `No` | `-` | `body` | `enrollmentId` | | **Description:** | The enrollment to check for completion | | | | | | | | | | | | ### Filter Parameters The `checkEnrollmentCompletion` api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `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/checkenrollmentcompletion?paymentConfirmation=active // Get records with multiple enum values (use multiple parameters) GET /v1/checkenrollmentcompletion?paymentConfirmation=active&paymentConfirmation=pending // Get records without this field GET /v1/checkenrollmentcompletion?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 `checkEnrollmentCompletion` 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: `[user, student, tutor, 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[3].businessLogic[12].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] Action : runCompletionCheck **Action Type**: `FunctionCallAction` Check and auto-complete enrollment if all lessons done ```js class Api { async runCompletionCheck() { try { return await runMScript( () => (async () => await LIB.checkEnrollmentCompletion( this.enrollmentId, this.session, ))(), { path: "services[3].businessLogic[12].actions.functionCallActions[0].callScript", }, ); } catch (err) { console.error("Error in FunctionCallAction runCompletionCheck:", err); throw err; } } } ``` --- ### [6] 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` --- ### [7] 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` --- ### [8] 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` --- ### [9] Step : buildOutput Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed. --- ### [10] Step : sendResponse Sends the paginated list to the client through the controller. --- ### [11] 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 `checkEnrollmentCompletion` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | The `checkEnrollmentCompletion` 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | 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 **POST /v1/checkenrollmentcompletion** ```js axios({ method: 'POST', url: '/v1/checkenrollmentcompletion', data: { enrollmentId:"ID", }, params: { // Filter parameters (see Filter Parameters section for usage examples) // 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 **`enrollments`** 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": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "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 - `Get Enrollmentpayment` # Business API Design Specification - `Get Enrollmentpayment` 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 `getEnrollmentPayment` 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 `getEnrollmentPayment` Business API is designed to handle a `get` operation on the `Sys_enrollmentPayment` 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 `enrollmentpayment-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 `getEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` 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 `getEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getEnrollmentPayment` 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_enrollmentPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_enrollmentPaymentId` | | **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 `getEnrollmentPayment` 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_enrollmentPaymentId},{isActive:true}]}), {"path":"services[3].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] 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 `getEnrollmentPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment`** 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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayments` # Business API Design Specification - `List Enrollmentpayments` 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 `listEnrollmentPayments` 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 `listEnrollmentPayments` Business API is designed to handle a `list` operation on the `Sys_enrollmentPayment` 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 `enrollmentpayments-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 `listEnrollmentPayments` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpayments` 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 `listEnrollmentPayments` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listEnrollmentPayments` 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 `listEnrollmentPayments` 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/enrollmentpayments?ownerId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/enrollmentpayments?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/enrollmentpayments?ownerId=null ``` #### `orderId` Filter **Type:** `ID` **Description:** an ID value to represent the orderId which is the ID parameter of the source enrollment 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/enrollmentpayments?orderId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/enrollmentpayments?orderId=550e8400-e29b-41d4-a716-446655440000&orderId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/enrollmentpayments?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/enrollmentpayments?paymentId=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/enrollmentpayments?paymentId=laptop&paymentId=phone&paymentId=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/enrollmentpayments?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/enrollmentpayments?paymentStatus=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/enrollmentpayments?paymentStatus=laptop&paymentStatus=phone&paymentStatus=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/enrollmentpayments?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/enrollmentpayments?statusLiteral=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/enrollmentpayments?statusLiteral=laptop&statusLiteral=phone&statusLiteral=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/enrollmentpayments?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/enrollmentpayments?redirectUrl=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/enrollmentpayments?redirectUrl=laptop&redirectUrl=phone&redirectUrl=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/enrollmentpayments?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 `listEnrollmentPayments` 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[3].businessLogic[14].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 `listEnrollmentPayments` 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 enrollment 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/enrollmentpayments** ```js axios({ method: 'GET', url: '/v1/enrollmentpayments', 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_enrollmentPayments`** 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_enrollmentPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_enrollmentPayments": [ { "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 Enrollmentpayment` # Business API Design Specification - `Create Enrollmentpayment` 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 `createEnrollmentPayment` 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 `createEnrollmentPayment` Business API is designed to handle a `create` operation on the `Sys_enrollmentPayment` 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 `enrollmentpayment-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 `createEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpayment` 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 `createEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createEnrollmentPayment` 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_enrollmentPaymentId` | `ID` | `No` | `-` | `body` | `sys_enrollmentPaymentId` | | **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 enrollment 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 `createEnrollmentPayment` 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_enrollmentPaymentId, 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 `createEnrollmentPayment` 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/enrollmentpayment** ```js axios({ method: 'POST', url: '/v1/enrollmentpayment', 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_enrollmentPayment`** 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_enrollmentPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` # Business API Design Specification - `Update Enrollmentpayment` 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 `updateEnrollmentPayment` 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 `updateEnrollmentPayment` Business API is designed to handle a `update` operation on the `Sys_enrollmentPayment` 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 `enrollmentpayment-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 `updateEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` 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 `updateEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateEnrollmentPayment` 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_enrollmentPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_enrollmentPaymentId` | | **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 `updateEnrollmentPayment` 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_enrollmentPaymentId},{isActive:true}]}), {"path":"services[3].businessLogic[16].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 `updateEnrollmentPayment` api has got 5 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | | 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/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'PATCH', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment`** 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_enrollmentPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` # Business API Design Specification - `Delete Enrollmentpayment` 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 `deleteEnrollmentPayment` 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 `deleteEnrollmentPayment` Business API is designed to handle a `delete` operation on the `Sys_enrollmentPayment` 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 `enrollmentpayment-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 `deleteEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` 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 `deleteEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteEnrollmentPayment` 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_enrollmentPaymentId` | `ID` | `Yes` | `-` | `urlpath` | `sys_enrollmentPaymentId` | | **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 `deleteEnrollmentPayment` 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_enrollmentPaymentId},{isActive:true}]}), {"path":"services[3].businessLogic[17].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 `deleteEnrollmentPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'DELETE', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, 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_enrollmentPayment`** 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_enrollmentPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpaymentbyorderid` # Business API Design Specification - `Get Enrollmentpaymentbyorderid` 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 `getEnrollmentPaymentByOrderId` 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 `getEnrollmentPaymentByOrderId` Business API is designed to handle a `get` operation on the `Sys_enrollmentPayment` 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 `enrollmentpaymentbyorderid-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 `getEnrollmentPaymentByOrderId` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpaymentbyorderid/: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 `getEnrollmentPaymentByOrderId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getEnrollmentPaymentByOrderId` 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 enrollment 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 `getEnrollmentPaymentByOrderId` 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[3].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 `getEnrollmentPaymentByOrderId` 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/enrollmentpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbyorderid/${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_enrollmentPayment`** 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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpaymentbypaymentid` # Business API Design Specification - `Get Enrollmentpaymentbypaymentid` 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 `getEnrollmentPaymentByPaymentId` 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 `getEnrollmentPaymentByPaymentId` Business API is designed to handle a `get` operation on the `Sys_enrollmentPayment` 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 `enrollmentpaymentbypaymentid-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 `getEnrollmentPaymentByPaymentId` Business API includes a REST controller that can be triggered via the following route: `/v1/enrollmentpaymentbypaymentid/: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 `getEnrollmentPaymentByPaymentId` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getEnrollmentPaymentByPaymentId` 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 `getEnrollmentPaymentByPaymentId` 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[3].businessLogic[19].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 `getEnrollmentPaymentByPaymentId` 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/enrollmentpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbypaymentid/${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_enrollmentPayment`** 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_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "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 Enrollmentpayment` # Business API Design Specification - `Start Enrollmentpayment` 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 `startEnrollmentPayment` 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 `startEnrollmentPayment` Business API is designed to handle a `update` operation on the `Enrollment` 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 enrollment ## 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 `enrollmentpayment-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 `startEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/startenrollmentpayment/:enrollmentId` 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 `startEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `startEnrollmentPayment` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `Yes` | `-` | `urlpath` | `enrollmentId` | | **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 `startEnrollmentPayment` 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.enrollmentId},{isActive:true}]}), {"path":"services[3].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 { paymentStatus: runMScript(() => (this.paymentStatus), {"path":"services[3].businessLogic[20].dataClause.customData[0].value"}), updatedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[20].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[3].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 { paymentStatus: runMScript(() => (this.paymentStatus), {"path":"services[3].businessLogic[20].dataClause.customData[0].value"}), updatedAt: runMScript(() => (new Date()), {"path":"services[3].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[3].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] 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[3].businessLogic[20].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.enrollmentId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-started"; case "updated": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-updated"; case "succeeded": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-succeeded"; case "failed": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-failed"; case "paymentdone": return "tutorhub-enrollmentmanagement-service-enrollment-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.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.paymentStatus = runMScript(() => "paid", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript( () => `Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}`, { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.description", }, ); const metadata = { order: "EnrollmentManagement-Enrollment-order", orderId: this.enrollment.id, paymentName: "enrollment", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.enrollment.totalAmount, currency: this.enrollment.currency, orderId: this.enrollment.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 `startEnrollmentPayment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/startenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/startenrollmentpayment/${enrollmentId}`, 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 **`enrollment`** 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 Enrollmentpayment` # Business API Design Specification - `Refresh Enrollmentpayment` 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 `refreshEnrollmentPayment` 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 `refreshEnrollmentPayment` Business API is designed to handle a `update` operation on the `Enrollment` 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 enrollment 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 `enrollmentpayment-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 `refreshEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/refreshenrollmentpayment/:enrollmentId` 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 `refreshEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `refreshEnrollmentPayment` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `Yes` | `-` | `urlpath` | `enrollmentId` | | **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 `refreshEnrollmentPayment` 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.enrollmentId},{isActive:true}]}), {"path":"services[3].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 { paymentStatus: runMScript(() => (this.paymentStatus), {"path":"services[3].businessLogic[21].dataClause.customData[0].value"}), updatedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[21].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[3].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 { paymentStatus: runMScript(() => (this.paymentStatus), {"path":"services[3].businessLogic[21].dataClause.customData[0].value"}), updatedAt: runMScript(() => (new Date()), {"path":"services[3].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[3].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] 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.enrollmentId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-started"; case "updated": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-updated"; case "succeeded": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-succeeded"; case "failed": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-failed"; case "paymentdone": return "tutorhub-enrollmentmanagement-service-enrollment-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.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.paymentStatus = runMScript(() => "paid", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript( () => `Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}`, { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.description", }, ); const metadata = { order: "EnrollmentManagement-Enrollment-order", orderId: this.enrollment.id, paymentName: "enrollment", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.enrollment.totalAmount, currency: this.enrollment.currency, orderId: this.enrollment.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 `refreshEnrollmentPayment` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/refreshenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/refreshenrollmentpayment/${enrollmentId}`, 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 **`enrollment`** 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": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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 Enrollmentpayment` # Business API Design Specification - `Callback Enrollmentpayment` 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 `callbackEnrollmentPayment` 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 `callbackEnrollmentPayment` Business API is designed to handle a `update` operation on the `Enrollment` 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 enrollment ## 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 `enrollmentpayment-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 `callbackEnrollmentPayment` Business API includes a REST controller that can be triggered via the following route: `/v1/callbackenrollmentpayment` 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 `callbackEnrollmentPayment` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `callbackEnrollmentPayment` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `enrollmentId` | `ID` | `No` | `-` | `body` | `enrollmentId` | | **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. * `enrollmentId`: ```javascript this.enrollmentId = runMScript(() => (this.paymentCallbackParams?.orderId), {"path":"services[3].businessLogic[22].customParameters[0].transform"}) ``` ## AUTH Configuration The **authentication and authorization configuration** defines the core access rules for the `callbackEnrollmentPayment` 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.enrollmentId},{isActive:true}]}), {"path":"services[3].businessLogic[22].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 { paymentStatus: runMScript(() => (this.paymentStatus), {"path":"services[3].businessLogic[22].dataClause.customData[0].value"}), updatedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[22].dataClause.customData[1].value"}), paymentConfirmation: runMScript(() => (this.paymentConfirmation), {"path":"services[3].businessLogic[22].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 { paymentStatus: runMScript(() => (this.paymentStatus), {"path":"services[3].businessLogic[22].dataClause.customData[0].value"}), updatedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[22].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[3].businessLogic[22].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[3].businessLogic[22].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.enrollmentId; } getPaymentStatusTopic(actionType) { switch (actionType) { case "started": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-started"; case "updated": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-updated"; case "succeeded": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-succeeded"; case "failed": return "tutorhub-enrollmentmanagement-service-enrollmentpaymentstatus-failed"; case "paymentdone": return "tutorhub-enrollmentmanagement-service-enrollment-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.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted", }); this.paymentConfirmation = "processing"; this.paymentManager.raisePaymentStatusEvent("started"); } async paymentCanceled() { this.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentFailed() { this.paymentStatus = runMScript(() => "pending", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed", }); this.paymentConfirmation = "canceled"; this.paymentManager.raisePaymentStatusEvent("failed"); } async paymentDone() { this.paymentStatus = runMScript(() => "paid", { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess", }); this.paymentConfirmation = "paid"; this.paymentManager.raisePaymentStatusEvent("succeeded"); } getPaymentParameters(userParams) { const description = runMScript( () => `Course: ${this.enrollment.coursePackId}, Student: ${this.enrollment.studentId}`, { path: "services[3].dataObjects[0].objectSettings.stripeOrder.configuration.description", }, ); const metadata = { order: "EnrollmentManagement-Enrollment-order", orderId: this.enrollment.id, paymentName: "enrollment", }; return { userId: this.session._USERID, fullname: this.session.fullname, email: this.session.email, description, amount: this.enrollment.totalAmount, currency: this.enrollment.currency, orderId: this.enrollment.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 `callbackEnrollmentPayment` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | false | request.body?.["enrollmentId"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/callbackenrollmentpayment** ```js axios({ method: 'POST', url: '/v1/callbackenrollmentpayment', data: { enrollmentId:"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 **`enrollment`** 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": "enrollment", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "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[3].businessLogic[23].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[3].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 `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[3].businessLogic[25].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 - `enrollmentManagement` # Service Library - `enrollmentManagement` This document provides a complete reference of the custom code library for the `enrollmentManagement` 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/")`. ### `getTutorProfileIdsByTutorId.js` ```js module.exports = async function getTutorProfileIdsByTutorId(userId) { // Fetch all tutorProfiles for this user from tutorCatalog const { fetchRemoteListByMQuery } = require("serviceCommon"); const profiles = await fetchRemoteListByMQuery("tutorProfile", { tutorId: userId }); return profiles.map(p => p.id); } ``` ### `validateEnrollmentConstraints.js` ```js module.exports = function validateEnrollmentConstraints(coursePack, lessonSlotIds, screeningMeetings, studentId, tutorUser) { if (!coursePack) return { valid: false, error: 'Course pack not found.' }; // 1. Course moderation check if (coursePack.moderationStatus === 'removed') { return { valid: false, error: 'This course has been removed and is no longer available for enrollment.' }; } if (coursePack.moderationStatus === 'flagged') { return { valid: false, error: 'This course is currently under review and cannot accept new enrollments.' }; } if (coursePack.isPublished === false) { return { valid: false, error: 'This course is not currently published.' }; } // 2. Tutor status check if (tutorUser) { if (tutorUser.accountStatus === 'banned') { return { valid: false, error: 'This tutor\'s account has been suspended. Enrollment is not available.' }; } if (tutorUser.accountStatus === 'suspended') { return { valid: false, error: 'This tutor\'s account is temporarily suspended. Please try again later.' }; } } // 3. Screening check if (coursePack.preliminaryMeetingRequired) { const approved = (screeningMeetings || []).find( m => m.studentId === studentId && m.tutorDecision === 'approved' ); if (!approved) return { valid: false, error: 'Screening approval is required before enrollment.' }; } // lessonSlotIds is the array of IDs from the request const slots = Array.isArray(lessonSlotIds) ? lessonSlotIds : []; const slotCount = slots.length; if (slotCount === 0) return { valid: false, error: 'At least one lesson slot is required.' }; // 4. Required classes count if (coursePack.requiredClassesCount && slotCount !== coursePack.requiredClassesCount) { return { valid: false, error: `This course requires exactly ${coursePack.requiredClassesCount} classes. Got ${slotCount}.` }; } return { valid: true, error: null }; } ``` ### `validateRefundEligibility.js` ```js module.exports = function validateRefundEligibility(enrollment, lessonSlots, paymentRecord) { if (!enrollment) return { eligible: false, error: 'Enrollment not found.' }; // Must be an active enrollment if (enrollment.enrollmentStatus !== 'active') { return { eligible: false, error: 'Only active enrollments can be refunded.' }; } // Must have paid status if (enrollment.paymentStatus !== 'paid') { return { eligible: false, error: 'Only paid enrollments can be refunded.' }; } // Must not already be refunded if (enrollment.refundStatus === 'processed') { return { eligible: false, error: 'This enrollment has already been refunded.' }; } // Must have a valid payment record with paymentId for Stripe refund if (!paymentRecord || !paymentRecord.paymentId) { return { eligible: false, error: 'No payment record found for this enrollment. Cannot process refund.' }; } // Check lesson completion status const slots = lessonSlots || []; const completedSlots = slots.filter(s => s.status === 'completed'); // --- PATH 1: Within 1 hour of enrollment → auto-approved instant refund --- const enrolledAt = enrollment.enrolledAt || enrollment.createdAt; const enrollmentTime = enrolledAt ? new Date(enrolledAt).getTime() : 0; const now = Date.now(); const oneHourMs = 60 * 60 * 1000; const withinOneHour = enrollmentTime > 0 && (now - enrollmentTime) <= oneHourMs; if (withinOneHour) { return { eligible: true, error: null, refundType: 'autoApproved', firstLessonCompleted: completedSlots.length >= 1, stripePaymentIntentId: paymentRecord.paymentId, refundAmount: enrollment.totalAmount, currency: enrollment.currency }; } // --- PATH 2: After first lesson completed (exactly 1) → pending admin review --- if (completedSlots.length === 1) { return { eligible: true, error: null, refundType: 'pendingReview', firstLessonCompleted: true, stripePaymentIntentId: paymentRecord.paymentId, refundAmount: enrollment.totalAmount, currency: enrollment.currency }; } // --- DENIED: No lessons completed (past 1 hour) --- if (completedSlots.length === 0) { return { eligible: false, error: 'The 1-hour instant refund window has passed. Refund is available after your first lesson is completed.' }; } // --- DENIED: More than 1 lesson completed --- return { eligible: false, error: 'Refund is no longer available after more than one lesson has been completed.' }; } ``` ### `cancelEnrollmentLessonSlots.js` ```js module.exports = async function cancelEnrollmentLessonSlots(lessonSlotIds, session) { if (!lessonSlotIds || !Array.isArray(lessonSlotIds) || lessonSlotIds.length === 0) { return { canceled: 0, errors: [] }; } const axios = require('axios'); const { getServiceSecret } = require('common'); // Build the courseScheduling M2M URL // In preview, services are on the same host with different routes const baseUrl = process.env.COURSESCHEDULING_API_URL || 'http://localhost:3002'; const m2mUrl = `${baseUrl}/m2m/updateLessonSlotById`; const serviceSecret = getServiceSecret ? getServiceSecret() : process.env.SERVICE_SECRET_KEY; let canceled = 0; const errors = []; for (const slotId of lessonSlotIds) { try { await axios.patch(m2mUrl, { id: slotId, dataClause: { status: 'canceled' } }, { headers: { 'Content-Type': 'application/json', ...(serviceSecret ? { 'x-service-secret': serviceSecret } : {}), ...(session?.token ? { 'Authorization': `Bearer ${session.token}` } : {}) }, timeout: 5000 }); canceled++; } catch (err) { errors.push({ slotId, error: err.message }); } } return { canceled, total: lessonSlotIds.length, errors }; } ``` ### `cancelAllTutorEnrollments.js` ```js module.exports = async function cancelAllTutorEnrollments(tutorProfileId, reason, session) { const { updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); const userQuery = { $and: [ { tutorProfileId: tutorProfileId }, { enrollmentStatus: 'active' }, { isActive: true } ] }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('enrollment'); const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; if (enrollments.length === 0) { return { canceled: 0, total: 0, errors: [], affectedStudentIds: [] }; } const context = { session, requestId: 'cascade-tutor-ban' }; let canceled = 0; const errors = []; const affectedStudentIds = []; for (const enrollment of enrollments) { try { await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'canceled', paymentStatus: 'refunded', refundStatus: 'processed' }, context); if (enrollment.studentId) affectedStudentIds.push(enrollment.studentId); if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) { try { const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots'); await cancelSlots(enrollment.lessonSlotIds, session); } catch (slotErr) { console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message); } } canceled++; } catch (err) { errors.push({ enrollmentId: enrollment.id, error: err.message }); } } return { canceled, total: enrollments.length, errors, affectedStudentIds: [...new Set(affectedStudentIds)] }; } ``` ### `cancelAllCourseEnrollments.js` ```js module.exports = async function cancelAllCourseEnrollments(coursePackId, reason, session) { const { updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); const userQuery = { $and: [ { coursePackId: coursePackId }, { enrollmentStatus: 'active' }, { isActive: true } ] }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('enrollment'); const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; if (enrollments.length === 0) { return { canceled: 0, total: 0, errors: [], affectedStudentIds: [] }; } const context = { session, requestId: 'cascade-course-removal' }; let canceled = 0; const errors = []; const affectedStudentIds = []; for (const enrollment of enrollments) { try { await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'canceled', paymentStatus: 'refunded', refundStatus: 'processed' }, context); if (enrollment.studentId) affectedStudentIds.push(enrollment.studentId); if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) { try { const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots'); await cancelSlots(enrollment.lessonSlotIds, session); } catch (slotErr) { console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message); } } canceled++; } catch (err) { errors.push({ enrollmentId: enrollment.id, error: err.message }); } } return { canceled, total: enrollments.length, errors, affectedStudentIds: [...new Set(affectedStudentIds)] }; } ``` ### `cleanupPendingEnrollments.js` ```js module.exports = async function cleanupPendingEnrollments(maxAgeMinutes, session) { const { updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); const cutoff = new Date(Date.now() - (maxAgeMinutes || 60) * 60 * 1000).toISOString(); // Find pending enrollments older than cutoff const userQuery = { $and: [ { enrollmentStatus: 'pending' }, { paymentStatus: 'pending' }, { createdAt: { $lt: cutoff } }, { isActive: true } ] }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('enrollment'); const enrollments = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; if (enrollments.length === 0) { return { cleaned: 0, total: 0, errors: [] }; } const context = { session: session || {}, requestId: 'cleanup-pending-enrollments' }; let cleaned = 0; const errors = []; for (const enrollment of enrollments) { try { // Cancel the enrollment await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'canceled', refundStatus: 'ineligible' }, context); // Free lesson slots if (enrollment.lessonSlotIds && Array.isArray(enrollment.lessonSlotIds)) { try { const cancelSlots = require('libFunctions/cancelEnrollmentLessonSlots'); await cancelSlots(enrollment.lessonSlotIds, session); } catch (slotErr) { console.log('Slot cleanup error for enrollment ' + enrollment.id + ':', slotErr.message); } } cleaned++; } catch (err) { errors.push({ enrollmentId: enrollment.id, error: err.message }); } } return { cleaned, total: enrollments.length, errors }; } ``` ### `checkEnrollmentCompletion.js` ```js module.exports = async function checkEnrollmentCompletion(enrollmentId, session) { const { getEnrollmentById, updateEnrollmentById } = require('dbLayer'); const { ElasticIndexer } = require('serviceCommon'); const { convertUserQueryToElasticQuery } = require('common'); if (!enrollmentId) return { updated: false, reason: 'No enrollmentId' }; // Fetch the enrollment const enrollment = await getEnrollmentById(enrollmentId); if (!enrollment) return { updated: false, reason: 'Enrollment not found' }; if (enrollment.enrollmentStatus !== 'active') return { updated: false, reason: 'Not active' }; const slotIds = enrollment.lessonSlotIds; if (!slotIds || !Array.isArray(slotIds) || slotIds.length === 0) { return { updated: false, reason: 'No lesson slots' }; } // Fetch all lesson slots from Elasticsearch const userQuery = { id: { $in: slotIds } }; const elasticQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer('lessonSlot'); const slots = (await elasticIndex.getDataByPage(0, 500, elasticQuery)) || []; // Check if ALL slots are completed const allCompleted = slots.length > 0 && slots.length === slotIds.length && slots.every(s => s.status === 'completed'); if (!allCompleted) { return { updated: false, reason: `${slots.filter(s => s.status === 'completed').length}/${slotIds.length} completed` }; } // Mark enrollment as completed const context = { session: session || {}, requestId: 'auto-complete-enrollment' }; await updateEnrollmentById(enrollmentId, { enrollmentStatus: 'completed' }, context); return { updated: true, enrollmentId }; } ``` ### `publishEnrichedRefundEvent.js` ```js module.exports = async function publishEnrichedRefundEvent(refundRequest, enrollment) { const { elasticClient, sendMessageToKafka } = require('common'); let student = null; let tutorUser = null; let coursePack = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source; const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } }); const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null; if (profile && profile.tutorId) { const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } }); if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source; } const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category'], size: 1 } }); if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source; } catch (err) { console.log('Warning: failed to fetch refund notification data from ES:', err.message); } const enrichedPayload = { id: refundRequest.id, enrollmentId: refundRequest.enrollmentId, status: refundRequest.status, reason: refundRequest.reason, requestedAt: refundRequest.requestedAt, processedAt: refundRequest.processedAt, totalAmount: enrollment.totalAmount, currency: enrollment.currency, student: student, tutorUser: tutorUser, coursePack: coursePack }; try { const topic = refundRequest.status === 'autoApproved' ? 'tutorhub-enrollmentmanagement-service-refund-processed' : 'tutorhub-enrollmentmanagement-service-refund-requested'; await sendMessageToKafka(topic, enrichedPayload); } catch (err) { console.log('Warning: failed to publish enriched refund event:', err.message); } } ``` ## Edge Functions 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. ### `deletePaymentMethodEdge.js` **Edge Controller:** - **Path:** `/payment-methods/delete/:paymentMethodId` - **Method:** `GET` - **Login Required:** Yes ```js const { getSys_paymentMethodByPaymentMethodId, deleteSys_paymentMethodById } = require('dbLayer'); const { stripeGateway } = require('common'); module.exports = async (request) => { const session = request.session; const paymentMethodId = request.params.paymentMethodId; if (!paymentMethodId) { return { status: 400, result: 'ERR', message: 'paymentMethodId is required' }; } const paymentMethodData = await getSys_paymentMethodByPaymentMethodId(paymentMethodId); if (!paymentMethodData) { return { status: 404, result: 'ERR', message: 'Payment method not found' }; } if (paymentMethodData.userId !== session.userId) { return { status: 403, result: 'ERR', message: 'Not authorized to delete this payment method' }; } try { if (Object.keys(stripeGateway).length > 0) { await stripeGateway.deletePaymentMethod(paymentMethodId); } } catch (stripeErr) { console.log('Stripe detach warning (proceeding with local delete):', stripeErr.message); } const deleted = await deleteSys_paymentMethodById(paymentMethodData.id); if (!deleted) { return { status: 500, result: 'ERR', message: 'Failed to delete payment method record' }; } return { status: 200, result: 'OK', message: 'Payment method deleted', data: deleted }; }; ``` ### `onEnrollmentPaymentDone.js` **Edge Controller:** - **Path:** `` - **Method:** `GET` - **Login Required:** No ```js const { updateEnrollmentById } = require('dbLayer'); const { elasticClient, sendMessageToKafka } = require('common'); module.exports = async (request) => { const enrollment = request.enrollment; if (!enrollment || !enrollment.id) return { status: 200, message: 'No enrollment to update' }; await updateEnrollmentById(enrollment.id, { enrollmentStatus: 'active', enrolledAt: new Date().toISOString() }); let student = null; let tutorUser = null; let coursePack = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source; const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } }); const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null; if (profile && profile.tutorId) { const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } }); if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source; } const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category', 'schedulingType'], size: 1 } }); if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source; } catch (err) { console.log('Warning: failed to fetch notification data from ES:', err.message); } try { await sendMessageToKafka('tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed', { id: enrollment.id, studentId: enrollment.studentId, coursePackId: enrollment.coursePackId, tutorProfileId: enrollment.tutorProfileId, totalAmount: enrollment.totalAmount, currency: enrollment.currency, student: student, tutorUser: tutorUser, coursePack: coursePack }); } catch (err) { console.log('Warning: failed to publish enriched enrollment event:', err.message); } return { status: 200, message: 'Enrollment activated' }; }; ``` ### `onRefundRequestCreated.js` **Edge Controller:** - **Path:** `` - **Method:** `GET` - **Login Required:** No ```js const { getEnrollmentById } = require('dbLayer'); const { elasticClient, sendMessageToKafka } = require('common'); module.exports = async (request) => { const payload = request.body || request.kafkaMessage || request; const dataSource = payload.dataSource || payload; if (!dataSource || !dataSource.enrollmentId) { console.log('onRefundRequestCreated: no enrollmentId in payload, skipping'); return { status: 200, message: 'Skipped - no enrollmentId' }; } const refundRequest = dataSource; let enrollment = null; try { enrollment = await getEnrollmentById(refundRequest.enrollmentId); } catch (err) { console.log('onRefundRequestCreated: failed to fetch enrollment:', err.message); return { status: 200, message: 'Skipped - enrollment not found' }; } if (!enrollment) { console.log('onRefundRequestCreated: enrollment not found for', refundRequest.enrollmentId); return { status: 200, message: 'Skipped - enrollment not found' }; } let student = null; let tutorUser = null; let coursePack = null; try { const studentRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 } }); if (studentRes.hits.hits.length > 0) student = studentRes.hits.hits[0]._source; const profileRes = await elasticClient.search({ index: 'tutorhub_tutorprofile', body: { query: { term: { id: enrollment.tutorProfileId } }, _source: ['tutorId'], size: 1 } }); const profile = profileRes.hits.hits.length > 0 ? profileRes.hits.hits[0]._source : null; if (profile && profile.tutorId) { const tutorRes = await elasticClient.search({ index: 'tutorhub_user', body: { query: { term: { id: profile.tutorId } }, _source: ['fullname', 'email'], size: 1 } }); if (tutorRes.hits.hits.length > 0) tutorUser = tutorRes.hits.hits[0]._source; } const packRes = await elasticClient.search({ index: 'tutorhub_coursepack', body: { query: { term: { id: enrollment.coursePackId } }, _source: ['title', 'category'], size: 1 } }); if (packRes.hits.hits.length > 0) coursePack = packRes.hits.hits[0]._source; } catch (err) { console.log('onRefundRequestCreated: failed to fetch enrichment data from ES:', err.message); } const enrichedPayload = { id: refundRequest.id, enrollmentId: refundRequest.enrollmentId, status: refundRequest.status, reason: refundRequest.reason, requestedAt: refundRequest.requestedAt, processedAt: refundRequest.processedAt, totalAmount: enrollment.totalAmount, currency: enrollment.currency, student: student, tutorUser: tutorUser, coursePack: coursePack }; try { const isAutoApproved = refundRequest.status === 'autoApproved' || refundRequest.status === 'autoapproved'; const topic = isAutoApproved ? 'tutorhub-enrollmentmanagement-service-refund-processed' : 'tutorhub-enrollmentmanagement-service-refund-requested'; await sendMessageToKafka(topic, enrichedPayload); console.log('onRefundRequestCreated: published to', topic); } catch (err) { console.log('onRefundRequestCreated: failed to publish enriched refund event:', err.message); } return { status: 200, message: 'Refund notification published' }; }; ``` ## Edge Controllers Summary | Function Name | Method | Path | Login Required | |--------------|--------|------|----------------| | `deletePaymentMethodEdge` | `GET` | `/payment-methods/delete/:paymentMethodId` | Yes | | `onRefundRequestCreated` | `GET` | `` | No | | `onEnrollmentPaymentDone` | `GET` | `` | No | --- *This document was generated from the service library configuration and should be kept in sync with design changes.* --- # PlatformAdmin Service ## Service Design Specification # Service Design Specification **tutorhub-platformadmin-service** documentation **Version:** `1.0.2` ## Scope This document provides a structured architectural overview of the `platformAdmin` 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. ## `PlatformAdmin` Service Settings ### Service Overview This service is configured to listen for HTTP requests on port `3005`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-platformadmin-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/platformadmin-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/platformadmin-api` * **Production:** `https://tutorhub.mindbricks.co/platformadmin-api` ### Authentication & Security - **Login Required**: Yes This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-platformadmin-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 | |-------------|-------------|---------------| | `adminIssue` | No description | accessPrivate | | `adminModerationAction` | Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. | accessPrivate | | `adminAnalyticsReport` | Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. | accessPrivate | ## adminIssue 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 | |----------|------|----------|-------------| | `reportedBy` | ID | Yes | User who filed the issue (student or tutor). | | `reportedUserId` | ID | No | (Optional) User being complained about | | `coursePackId` | ID | No | (Optional) ID of the related coursePack, if content/pack is complained about | | `description` | Text | Yes | Long text/body of the complaint/issue. | | `issueType` | Enum | Yes | Type of complaint (user, content, or other). | | `status` | Enum | Yes | Issue investigation status (open/investigating/resolved/dismissed). | | `adminNote` | String | No | Internal/admin note for progress or findings (not visible to original user). | | `resolution` | Enum | No | Resolution outcome chosen by admin when closing the issue. | * 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. - **reportedBy**: '00000000-0000-0000-0000-000000000000' - **description**: 'text' - **issueType**: user - **status**: open ### Constant Properties `reportedBy` 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 `reportedUserId` `coursePackId` `description` `issueType` `status` `adminNote` `resolution` 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. - **issueType**: [user, content, other] - **status**: [open, investigating, resolved, dismissed] - **resolution**: [dismissed, warned, courseEditRequired, courseRemoved, userSuspended, userBanned, acknowledged] ### Elastic Search Indexing `reportedBy` `reportedUserId` `coursePackId` `description` `issueType` `status` `resolution` 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 `reportedBy` `reportedUserId` `coursePackId` `issueType` `status` `resolution` 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 `reportedBy` `reportedUserId` `coursePackId` 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. - **reportedBy**: 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 - **reportedUserId**: 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: No - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: No ## adminModerationAction Data Object ### Object Overview **Description:** Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. 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 - **uniqueModerationPerTargetDate**: [targetType, targetId, actionDate] 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 | |----------|------|----------|-------------| | `adminId` | ID | Yes | Admin performing moderation action. | | `targetType` | Enum | Yes | Moderation target type (user/coursePack/profile/material). | | `targetId` | ID | Yes | ID of moderation target object (userId, coursePackId, etc). | | `actionType` | Enum | Yes | Type of moderation action (suspend, ban, edit, remove, approve, warn). | | `actionReason` | String | Yes | Reason for moderation action, as recorded by the admin. | | `actionDate` | Date | Yes | Datetime when the action took place. | | `targetUserId` | ID | Yes | UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content. | * 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. - **adminId**: '00000000-0000-0000-0000-000000000000' - **targetType**: "user" - **targetId**: '00000000-0000-0000-0000-000000000000' - **actionType**: "suspend" - **actionReason**: 'default' - **actionDate**: new Date() - **targetUserId**: '00000000-0000-0000-0000-000000000000' ### Constant Properties `adminId` `targetType` `targetId` `actionType` `actionReason` `actionDate` `targetUserId` 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. - **targetType**: [user, coursePack, profile, material] - **actionType**: [suspend, ban, edit, remove, approve, warn] ### Elastic Search Indexing `adminId` `targetType` `targetId` `actionType` `actionReason` `actionDate` `targetUserId` 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 `adminId` `targetType` `targetId` `actionType` `actionDate` `targetUserId` 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 `adminId` `targetUserId` 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. - **adminId**: 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 - **targetUserId**: 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 ## adminAnalyticsReport Data Object ### Object Overview **Description:** Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. 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 | |----------|------|----------|-------------| | `reportType` | String | Yes | Type of the analytics report (enrollments, revenue, complaints, etc). | | `filterParams` | String | No | Filter params as stringified JSON for reporting input. | | `generatedAt` | Date | Yes | Date/time report was generated. | | `reportUrl` | String | Yes | Accessible URL where generated report is stored (PDF, CSV, etc). | * 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. - **reportType**: 'default' - **generatedAt**: new Date() - **reportUrl**: 'default' ### Constant Properties `reportType` `filterParams` `generatedAt` `reportUrl` 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 `reportType` `generatedAt` 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 `reportType` `generatedAt` 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. ## Business Logic platformAdmin has got 11 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Create Adminissue](/document/businessLogic/createadminissue) * [Update Adminissue](/document/businessLogic/updateadminissue) * [Get Adminissue](/document/businessLogic/getadminissue) * [List Adminissues](/document/businessLogic/listadminissues) * [Create Adminmoderationaction](/document/businessLogic/createadminmoderationaction) * [Get Adminmoderationaction](/document/businessLogic/getadminmoderationaction) * [List Adminmoderationactions](/document/businessLogic/listadminmoderationactions) * [Create Adminanalyticsreport](/document/businessLogic/createadminanalyticsreport) * [Get Adminanalyticsreport](/document/businessLogic/getadminanalyticsreport) * [List Adminanalyticsreports](/document/businessLogic/listadminanalyticsreports) * [List Myissues](/document/businessLogic/listmyissues) --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## tutorhub-platformadmin-service **Version:** `1.0.2` ## 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 PlatformAdmin Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our PlatformAdmin Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the PlatformAdmin Service via HTTP requests for purposes such as creating, updating, deleting and querying PlatformAdmin 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 PlatformAdmin 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 PlatformAdmin 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 | tutorhub-access-token| | Cookie | tutorhub-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 PlatformAdmin 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 PlatformAdmin service. This service is configured to listen for HTTP requests on port `3005`, 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://tutorhub.prw.mindbricks.com/platformadmin-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/platformadmin-api` * **Production:** `https://tutorhub.mindbricks.co/platformadmin-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 PlatformAdmin 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 `PlatformAdmin` 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 `PlatformAdmin` 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 `PlatformAdmin` 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 PlatformAdmin 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. ### AdminIssue resource *AdminIssue Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **reportedBy** | ID | | | *User who filed the issue (student or tutor).* | | **reportedUserId** | ID | | | *(Optional) User being complained about* | | **coursePackId** | ID | | | *(Optional) ID of the related coursePack, if content/pack is complained about* | | **description** | Text | | | *Long text/body of the complaint/issue.* | | **issueType** | Enum | | | *Type of complaint (user, content, or other).* | | **status** | Enum | | | *Issue investigation status (open/investigating/resolved/dismissed).* | | **adminNote** | String | | | *Internal/admin note for progress or findings (not visible to original user).* | | **resolution** | Enum | | | *Resolution outcome chosen by admin when closing the issue.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### issueType Enum Property *Property Definition* : Type of complaint (user, content, or other).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **user** | `"user""` | 0 | | **content** | `"content""` | 1 | | **other** | `"other""` | 2 | ##### status Enum Property *Property Definition* : Issue investigation status (open/investigating/resolved/dismissed).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **open** | `"open""` | 0 | | **investigating** | `"investigating""` | 1 | | **resolved** | `"resolved""` | 2 | | **dismissed** | `"dismissed""` | 3 | ##### resolution Enum Property *Property Definition* : Resolution outcome chosen by admin when closing the issue.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **dismissed** | `"dismissed""` | 0 | | **warned** | `"warned""` | 1 | | **courseEditRequired** | `"courseEditRequired""` | 2 | | **courseRemoved** | `"courseRemoved""` | 3 | | **userSuspended** | `"userSuspended""` | 4 | | **userBanned** | `"userBanned""` | 5 | | **acknowledged** | `"acknowledged""` | 6 | ### AdminModerationAction resource *Resource Definition* : Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. *AdminModerationAction Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **adminId** | ID | | | *Admin performing moderation action.* | | **targetType** | Enum | | | *Moderation target type (user/coursePack/profile/material).* | | **targetId** | ID | | | *ID of moderation target object (userId, coursePackId, etc).* | | **actionType** | Enum | | | *Type of moderation action (suspend, ban, edit, remove, approve, warn).* | | **actionReason** | String | | | *Reason for moderation action, as recorded by the admin.* | | **actionDate** | Date | | | *Datetime when the action took place.* | | **targetUserId** | ID | | | *UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### targetType Enum Property *Property Definition* : Moderation target type (user/coursePack/profile/material).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **user** | `"user""` | 0 | | **coursePack** | `"coursePack""` | 1 | | **profile** | `"profile""` | 2 | | **material** | `"material""` | 3 | ##### actionType Enum Property *Property Definition* : Type of moderation action (suspend, ban, edit, remove, approve, warn).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **suspend** | `"suspend""` | 0 | | **ban** | `"ban""` | 1 | | **edit** | `"edit""` | 2 | | **remove** | `"remove""` | 3 | | **approve** | `"approve""` | 4 | | **warn** | `"warn""` | 5 | ### AdminAnalyticsReport resource *Resource Definition* : Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. *AdminAnalyticsReport Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **reportType** | String | | | *Type of the analytics report (enrollments, revenue, complaints, etc).* | | **filterParams** | String | | | *Filter params as stringified JSON for reporting input.* | | **generatedAt** | Date | | | *Date/time report was generated.* | | **reportUrl** | String | | | *Accessible URL where generated report is stored (PDF, CSV, etc).* | ## Business Api ### `Create Adminissue` API **[Default create API]** — This is the designated default `create` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student or tutor files a new complaint/issue. Admin receives for review/investigation. Only admins can update or alter status; creator can get their own. **Rest Route** The `createAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues` **Rest Request Parameters** The `createAdminIssue` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportedBy | ID | true | request.body?.["reportedBy"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | true | request.body?.["description"] | | issueType | Enum | true | request.body?.["issueType"] | | status | Enum | true | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | **reportedBy** : User who filed the issue (student or tutor). **reportedUserId** : (Optional) User being complained about **coursePackId** : (Optional) ID of the related coursePack, if content/pack is complained about **description** : Long text/body of the complaint/issue. **issueType** : Type of complaint (user, content, or other). **status** : Issue investigation status (open/investigating/resolved/dismissed). **adminNote** : Internal/admin note for progress or findings (not visible to original user). **resolution** : Resolution outcome chosen by admin when closing the issue. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminissues** ```js axios({ method: 'POST', url: '/v1/adminissues', data: { reportedBy:"ID", reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Adminissue` API **[Default update API]** — This is the designated default `update` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin investigates/updates an issue: change status, add internal note, resolve/dismiss. Strictly admin-only. **Rest Route** The `updateAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues/:adminIssueId` **Rest Request Parameters** The `updateAdminIssue` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | false | request.body?.["description"] | | issueType | Enum | false | request.body?.["issueType"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | **adminIssueId** : This id paremeter is used to select the required data object that will be updated **reportedUserId** : (Optional) User being complained about **coursePackId** : (Optional) ID of the related coursePack, if content/pack is complained about **description** : Long text/body of the complaint/issue. **issueType** : Type of complaint (user, content, or other). **status** : Issue investigation status (open/investigating/resolved/dismissed). **adminNote** : Internal/admin note for progress or findings (not visible to original user). **resolution** : Resolution outcome chosen by admin when closing the issue. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/adminissues/:adminIssueId** ```js axios({ method: 'PATCH', url: `/v1/adminissues/${adminIssueId}`, data: { reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "reporterUser": {} } ``` ### `Get Adminissue` API **[Default get API]** — This is the designated default `get` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetches a single issue by ID. Admins may get any; creator may get/view their own for status updates. **Rest Route** The `getAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues/:adminIssueId` **Rest Request Parameters** The `getAdminIssue` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | **adminIssueId** : 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/adminissues/:adminIssueId** ```js axios({ method: 'GET', url: `/v1/adminissues/${adminIssueId}`, 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": "adminIssue", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminIssue": { "reporter": { "email": "String", "fullname": "String" }, "reportedUser": { "email": "String", "fullname": "String" }, "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` ### `List Adminissues` API **[Default list API]** — This is the designated default `list` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List issues with filters for admin dashboard: by status/type/target. Admin only. **Rest Route** The `listAdminIssues` API REST controller can be triggered via the following route: `/v1/adminissues` **Rest Request Parameters** The `listAdminIssues` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminissues** ```js axios({ method: 'GET', url: '/v1/adminissues', 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": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reporter": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "reportedUser": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Adminmoderationaction` API **[Default create API]** — This is the designated default `create` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin records a moderation action against a user/object. Admin only. Write-side audit log for all moderator events. **Rest Route** The `createAdminModerationAction` API REST controller can be triggered via the following route: `/v1/adminmoderationactions` **Rest Request Parameters** The `createAdminModerationAction` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminId | ID | true | request.body?.["adminId"] | | targetType | Enum | true | request.body?.["targetType"] | | targetId | ID | true | request.body?.["targetId"] | | actionType | Enum | true | request.body?.["actionType"] | | actionReason | String | true | request.body?.["actionReason"] | | actionDate | Date | true | request.body?.["actionDate"] | | targetUserId | ID | true | request.body?.["targetUserId"] | **adminId** : Admin performing moderation action. **targetType** : Moderation target type (user/coursePack/profile/material). **targetId** : ID of moderation target object (userId, coursePackId, etc). **actionType** : Type of moderation action (suspend, ban, edit, remove, approve, warn). **actionReason** : Reason for moderation action, as recorded by the admin. **actionDate** : Datetime when the action took place. **targetUserId** : UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminmoderationactions** ```js axios({ method: 'POST', url: '/v1/adminmoderationactions', data: { adminId:"ID", targetType:"Enum", targetId:"ID", actionType:"Enum", actionReason:"String", actionDate:"Date", targetUserId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminModerationAction", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "id": "ID", "adminId": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "actionType": "Enum", "actionType_idx": "Integer", "actionReason": "String", "actionDate": "Date", "targetUserId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "targetUser": {} } ``` ### `Get Adminmoderationaction` API **[Default get API]** — This is the designated default `get` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one moderation action. Admin only. **Rest Route** The `getAdminModerationAction` API REST controller can be triggered via the following route: `/v1/adminmoderationactions/:adminModerationActionId` **Rest Request Parameters** The `getAdminModerationAction` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminModerationActionId | ID | true | request.params?.["adminModerationActionId"] | **adminModerationActionId** : 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/adminmoderationactions/:adminModerationActionId** ```js axios({ method: 'GET', url: `/v1/adminmoderationactions/${adminModerationActionId}`, 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": "adminModerationAction", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "admin": { "email": "String", "fullname": "String" }, "isActive": true } } ``` ### `List Adminmoderationactions` API **[Default list API]** — This is the designated default `list` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all admin moderation actions, filterable by actionType/targetType/date. For admin dashboard audit log. **Rest Route** The `listAdminModerationActions` API REST controller can be triggered via the following route: `/v1/adminmoderationactions` **Rest Request Parameters** The `listAdminModerationActions` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminmoderationactions** ```js axios({ method: 'GET', url: '/v1/adminmoderationactions', 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": "adminModerationActions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminModerationActions": [ { "admin": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Adminanalyticsreport` API **[Default create API]** — This is the designated default `create` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create record for a new analytics report (usually admin-triggered on dashboard, actual report process may be async via edge controller in future). Admin-only; records metadata and download URL of available report. **Rest Route** The `createAdminAnalyticsReport` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports` **Rest Request Parameters** The `createAdminAnalyticsReport` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportType | String | true | request.body?.["reportType"] | | filterParams | String | false | request.body?.["filterParams"] | | generatedAt | Date | true | request.body?.["generatedAt"] | | reportUrl | String | true | request.body?.["reportUrl"] | **reportType** : Type of the analytics report (enrollments, revenue, complaints, etc). **filterParams** : Filter params as stringified JSON for reporting input. **generatedAt** : Date/time report was generated. **reportUrl** : Accessible URL where generated report is stored (PDF, CSV, etc). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminanalyticsreports** ```js axios({ method: 'POST', url: '/v1/adminanalyticsreports', data: { reportType:"String", filterParams:"String", generatedAt:"Date", reportUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminAnalyticsReport", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "id": "ID", "reportType": "String", "filterParams": "String", "generatedAt": "Date", "reportUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Adminanalyticsreport` API **[Default get API]** — This is the designated default `get` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one analytics report record for download from admin dashboard. Admin only. **Rest Route** The `getAdminAnalyticsReport` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports/:adminAnalyticsReportId` **Rest Request Parameters** The `getAdminAnalyticsReport` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminAnalyticsReportId | ID | true | request.params?.["adminAnalyticsReportId"] | **adminAnalyticsReportId** : 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/adminanalyticsreports/:adminAnalyticsReportId** ```js axios({ method: 'GET', url: `/v1/adminanalyticsreports/${adminAnalyticsReportId}`, 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": "adminAnalyticsReport", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "isActive": true } } ``` ### `List Adminanalyticsreports` API **[Default list API]** — This is the designated default `list` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all analytics reports for admin dashboard access (download/view). Admin only. **Rest Route** The `listAdminAnalyticsReports` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports` **Rest Request Parameters** The `listAdminAnalyticsReports` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminanalyticsreports** ```js axios({ method: 'GET', url: '/v1/adminanalyticsreports', 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": "adminAnalyticsReports", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminAnalyticsReports": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Myissues` API Students and tutors list their own reported issues. Ownership check ensures users only see their own reports. **Rest Route** The `listMyIssues` API REST controller can be triggered via the following route: `/v1/myissues` **Rest Request Parameters** The `listMyIssues` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myissues** ```js axios({ method: 'GET', url: '/v1/myissues', 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": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reportedUser": [ { "email": "String", "fullname": "String" }, {}, {} ], "coursePack": [ { "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "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 ## tutorhub-platformadmin-service ## 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 `PlatformAdmin` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `PlatformAdmin` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `PlatformAdmin` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `PlatformAdmin` 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 `PlatformAdmin` 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 adminIssue-created **Event topic**: `tutorhub-platformadmin-service-dbevent-adminissue-created` This event is triggered upon the creation of a `adminIssue` 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","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent adminIssue-updated **Event topic**: `tutorhub-platformadmin-service-dbevent-adminissue-updated` Activation of this event follows the update of a `adminIssue` data object. The payload contains the updated information under the `adminIssue` attribute, along with the original data prior to update, labeled as `old_adminIssue` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_adminIssue:{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, adminIssue:{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent adminIssue-deleted **Event topic**: `tutorhub-platformadmin-service-dbevent-adminissue-deleted` This event announces the deletion of a `adminIssue` 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","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent adminModerationAction-created **Event topic**: `tutorhub-platformadmin-service-dbevent-adminmoderationaction-created` This event is triggered upon the creation of a `adminModerationAction` 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","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent adminModerationAction-updated **Event topic**: `tutorhub-platformadmin-service-dbevent-adminmoderationaction-updated` Activation of this event follows the update of a `adminModerationAction` data object. The payload contains the updated information under the `adminModerationAction` attribute, along with the original data prior to update, labeled as `old_adminModerationAction` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_adminModerationAction:{"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, adminModerationAction:{"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent adminModerationAction-deleted **Event topic**: `tutorhub-platformadmin-service-dbevent-adminmoderationaction-deleted` This event announces the deletion of a `adminModerationAction` 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","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent adminAnalyticsReport-created **Event topic**: `tutorhub-platformadmin-service-dbevent-adminanalyticsreport-created` This event is triggered upon the creation of a `adminAnalyticsReport` 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","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent adminAnalyticsReport-updated **Event topic**: `tutorhub-platformadmin-service-dbevent-adminanalyticsreport-updated` Activation of this event follows the update of a `adminAnalyticsReport` data object. The payload contains the updated information under the `adminAnalyticsReport` attribute, along with the original data prior to update, labeled as `old_adminAnalyticsReport` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_adminAnalyticsReport:{"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, adminAnalyticsReport:{"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent adminAnalyticsReport-deleted **Event topic**: `tutorhub-platformadmin-service-dbevent-adminanalyticsreport-deleted` This event announces the deletion of a `adminAnalyticsReport` 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","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` # ElasticSearch Index Events Within the `PlatformAdmin` 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 adminissue-created **Event topic**: `elastic-index-tutorhub_adminissue-created` **Event payload**: ```json {"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminissue-updated **Event topic**: `elastic-index-tutorhub_adminissue-created` **Event payload**: ```json {"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminissue-deleted **Event topic**: `elastic-index-tutorhub_adminissue-deleted` **Event payload**: ```json {"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminissue-extended **Event topic**: `elastic-index-tutorhub_adminissue-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 adminissue-created **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** 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":"adminIssue","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminIssue":{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event adminissue-updated **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssue","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"adminIssue":{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"reporterUser":{}} ``` ## Route Event adminissue-retrived **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssue","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminIssue":{"reporter":{"email":"String","fullname":"String"},"reportedUser":{"email":"String","fullname":"String"},"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event adminissues-listed **Event topic** : `tutorhub-platformadmin-service-adminissues-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 `adminIssues` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssues`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssues","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminIssues":[{"reporter":[{"email":"String","fullname":"String","roleId":"String"},{},{}],"reportedUser":[{"email":"String","fullname":"String","roleId":"String"},{},{}],"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event adminmoderationaction-created **Event topic** : `tutorhub-platformadmin-service-adminmoderationaction-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 `adminModerationAction` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationAction`** 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":"adminModerationAction","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminModerationAction":{"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"targetUser":{}} ``` ## Route Event adminmoderationaction-retrived **Event topic** : `tutorhub-platformadmin-service-adminmoderationaction-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 `adminModerationAction` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationAction`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminModerationAction","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminModerationAction":{"admin":{"email":"String","fullname":"String"},"isActive":true}} ``` ## Route Event adminmoderationactions-listed **Event topic** : `tutorhub-platformadmin-service-adminmoderationactions-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 `adminModerationActions` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationActions`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminModerationActions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminModerationActions":[{"admin":[{"email":"String","fullname":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event adminanalyticsreport-created **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreport-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 `adminAnalyticsReport` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReport`** 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":"adminAnalyticsReport","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminAnalyticsReport":{"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event adminanalyticsreport-retrived **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreport-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 `adminAnalyticsReport` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReport`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminAnalyticsReport","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminAnalyticsReport":{"isActive":true}} ``` ## Route Event adminanalyticsreports-listed **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreports-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 `adminAnalyticsReports` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReports`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminAnalyticsReports","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminAnalyticsReports":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event adminmoderationaction-created **Event topic**: `elastic-index-tutorhub_adminmoderationaction-created` **Event payload**: ```json {"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminmoderationaction-updated **Event topic**: `elastic-index-tutorhub_adminmoderationaction-created` **Event payload**: ```json {"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminmoderationaction-deleted **Event topic**: `elastic-index-tutorhub_adminmoderationaction-deleted` **Event payload**: ```json {"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminmoderationaction-extended **Event topic**: `elastic-index-tutorhub_adminmoderationaction-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 adminissue-created **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** 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":"adminIssue","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminIssue":{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event adminissue-updated **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssue","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"adminIssue":{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"reporterUser":{}} ``` ## Route Event adminissue-retrived **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssue","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminIssue":{"reporter":{"email":"String","fullname":"String"},"reportedUser":{"email":"String","fullname":"String"},"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event adminissues-listed **Event topic** : `tutorhub-platformadmin-service-adminissues-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 `adminIssues` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssues`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssues","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminIssues":[{"reporter":[{"email":"String","fullname":"String","roleId":"String"},{},{}],"reportedUser":[{"email":"String","fullname":"String","roleId":"String"},{},{}],"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event adminmoderationaction-created **Event topic** : `tutorhub-platformadmin-service-adminmoderationaction-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 `adminModerationAction` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationAction`** 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":"adminModerationAction","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminModerationAction":{"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"targetUser":{}} ``` ## Route Event adminmoderationaction-retrived **Event topic** : `tutorhub-platformadmin-service-adminmoderationaction-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 `adminModerationAction` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationAction`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminModerationAction","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminModerationAction":{"admin":{"email":"String","fullname":"String"},"isActive":true}} ``` ## Route Event adminmoderationactions-listed **Event topic** : `tutorhub-platformadmin-service-adminmoderationactions-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 `adminModerationActions` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationActions`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminModerationActions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminModerationActions":[{"admin":[{"email":"String","fullname":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event adminanalyticsreport-created **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreport-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 `adminAnalyticsReport` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReport`** 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":"adminAnalyticsReport","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminAnalyticsReport":{"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event adminanalyticsreport-retrived **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreport-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 `adminAnalyticsReport` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReport`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminAnalyticsReport","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminAnalyticsReport":{"isActive":true}} ``` ## Route Event adminanalyticsreports-listed **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreports-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 `adminAnalyticsReports` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReports`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminAnalyticsReports","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminAnalyticsReports":[{"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Index Event adminanalyticsreport-created **Event topic**: `elastic-index-tutorhub_adminanalyticsreport-created` **Event payload**: ```json {"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminanalyticsreport-updated **Event topic**: `elastic-index-tutorhub_adminanalyticsreport-created` **Event payload**: ```json {"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminanalyticsreport-deleted **Event topic**: `elastic-index-tutorhub_adminanalyticsreport-deleted` **Event payload**: ```json {"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event adminanalyticsreport-extended **Event topic**: `elastic-index-tutorhub_adminanalyticsreport-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 adminissue-created **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** 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":"adminIssue","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminIssue":{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event adminissue-updated **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssue","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"adminIssue":{"id":"ID","reportedBy":"ID","reportedUserId":"ID","coursePackId":"ID","description":"Text","issueType":"Enum","issueType_idx":"Integer","status":"Enum","status_idx":"Integer","adminNote":"String","resolution":"Enum","resolution_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"reporterUser":{}} ``` ## Route Event adminissue-retrived **Event topic** : `tutorhub-platformadmin-service-adminissue-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 `adminIssue` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssue`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssue","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminIssue":{"reporter":{"email":"String","fullname":"String"},"reportedUser":{"email":"String","fullname":"String"},"coursePack":{"tutorProfileId":"ID","title":"String"},"isActive":true}} ``` ## Route Event adminissues-listed **Event topic** : `tutorhub-platformadmin-service-adminissues-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 `adminIssues` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminIssues`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminIssues","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminIssues":[{"reporter":[{"email":"String","fullname":"String","roleId":"String"},{},{}],"reportedUser":[{"email":"String","fullname":"String","roleId":"String"},{},{}],"coursePack":[{"tutorProfileId":"ID","title":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event adminmoderationaction-created **Event topic** : `tutorhub-platformadmin-service-adminmoderationaction-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 `adminModerationAction` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationAction`** 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":"adminModerationAction","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminModerationAction":{"id":"ID","adminId":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","actionType":"Enum","actionType_idx":"Integer","actionReason":"String","actionDate":"Date","targetUserId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"targetUser":{}} ``` ## Route Event adminmoderationaction-retrived **Event topic** : `tutorhub-platformadmin-service-adminmoderationaction-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 `adminModerationAction` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationAction`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminModerationAction","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminModerationAction":{"admin":{"email":"String","fullname":"String"},"isActive":true}} ``` ## Route Event adminmoderationactions-listed **Event topic** : `tutorhub-platformadmin-service-adminmoderationactions-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 `adminModerationActions` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminModerationActions`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminModerationActions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminModerationActions":[{"admin":[{"email":"String","fullname":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]} ``` ## Route Event adminanalyticsreport-created **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreport-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 `adminAnalyticsReport` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReport`** 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":"adminAnalyticsReport","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminAnalyticsReport":{"id":"ID","reportType":"String","filterParams":"String","generatedAt":"Date","reportUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event adminanalyticsreport-retrived **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreport-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 `adminAnalyticsReport` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReport`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminAnalyticsReport","method":"GET","action":"get","appVersion":"Version","rowCount":1,"adminAnalyticsReport":{"isActive":true}} ``` ## Route Event adminanalyticsreports-listed **Event topic** : `tutorhub-platformadmin-service-adminanalyticsreports-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 `adminAnalyticsReports` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`adminAnalyticsReports`** object. Note, however, that certain properties might be excluded in accordance with the object's inherent logic. ```json {"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"adminAnalyticsReports","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","adminAnalyticsReports":[{"isActive":true},{},{}],"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 adminIssue # Service Design Specification - Object Design for adminIssue **tutorhub-platformadmin-service** documentation ## Document Overview This document outlines the object design for the `adminIssue` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## adminIssue 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 | |----------|------|----------|-------------| | `reportedBy` | ID | Yes | User who filed the issue (student or tutor). | | `reportedUserId` | ID | No | (Optional) User being complained about | | `coursePackId` | ID | No | (Optional) ID of the related coursePack, if content/pack is complained about | | `description` | Text | Yes | Long text/body of the complaint/issue. | | `issueType` | Enum | Yes | Type of complaint (user, content, or other). | | `status` | Enum | Yes | Issue investigation status (open/investigating/resolved/dismissed). | | `adminNote` | String | No | Internal/admin note for progress or findings (not visible to original user). | | `resolution` | Enum | No | Resolution outcome chosen by admin when closing the issue. | * 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. - **reportedBy**: '00000000-0000-0000-0000-000000000000' - **description**: 'text' - **issueType**: user - **status**: open ### Constant Properties `reportedBy` 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 `reportedUserId` `coursePackId` `description` `issueType` `status` `adminNote` `resolution` 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. - **issueType**: [user, content, other] - **status**: [open, investigating, resolved, dismissed] - **resolution**: [dismissed, warned, courseEditRequired, courseRemoved, userSuspended, userBanned, acknowledged] ### Elastic Search Indexing `reportedBy` `reportedUserId` `coursePackId` `description` `issueType` `status` `resolution` 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 `reportedBy` `reportedUserId` `coursePackId` `issueType` `status` `resolution` 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 `reportedBy` `reportedUserId` `coursePackId` 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. - **reportedBy**: 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 - **reportedUserId**: 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: No - **coursePackId**: ID Relation to `coursePack`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: No --- ### Service Design Specification - Object Design for adminModerationAction # Service Design Specification - Object Design for adminModerationAction **tutorhub-platformadmin-service** documentation ## Document Overview This document outlines the object design for the `adminModerationAction` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## adminModerationAction Data Object ### Object Overview **Description:** Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. 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 - **uniqueModerationPerTargetDate**: [targetType, targetId, actionDate] 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 | |----------|------|----------|-------------| | `adminId` | ID | Yes | Admin performing moderation action. | | `targetType` | Enum | Yes | Moderation target type (user/coursePack/profile/material). | | `targetId` | ID | Yes | ID of moderation target object (userId, coursePackId, etc). | | `actionType` | Enum | Yes | Type of moderation action (suspend, ban, edit, remove, approve, warn). | | `actionReason` | String | Yes | Reason for moderation action, as recorded by the admin. | | `actionDate` | Date | Yes | Datetime when the action took place. | | `targetUserId` | ID | Yes | UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content. | * 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. - **adminId**: '00000000-0000-0000-0000-000000000000' - **targetType**: "user" - **targetId**: '00000000-0000-0000-0000-000000000000' - **actionType**: "suspend" - **actionReason**: 'default' - **actionDate**: new Date() - **targetUserId**: '00000000-0000-0000-0000-000000000000' ### Constant Properties `adminId` `targetType` `targetId` `actionType` `actionReason` `actionDate` `targetUserId` 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. - **targetType**: [user, coursePack, profile, material] - **actionType**: [suspend, ban, edit, remove, approve, warn] ### Elastic Search Indexing `adminId` `targetType` `targetId` `actionType` `actionReason` `actionDate` `targetUserId` 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 `adminId` `targetType` `targetId` `actionType` `actionDate` `targetUserId` 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 `adminId` `targetUserId` 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. - **adminId**: 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 - **targetUserId**: 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 --- ### Service Design Specification - Object Design for adminAnalyticsReport # Service Design Specification - Object Design for adminAnalyticsReport **tutorhub-platformadmin-service** documentation ## Document Overview This document outlines the object design for the `adminAnalyticsReport` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## adminAnalyticsReport Data Object ### Object Overview **Description:** Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. 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 | |----------|------|----------|-------------| | `reportType` | String | Yes | Type of the analytics report (enrollments, revenue, complaints, etc). | | `filterParams` | String | No | Filter params as stringified JSON for reporting input. | | `generatedAt` | Date | Yes | Date/time report was generated. | | `reportUrl` | String | Yes | Accessible URL where generated report is stored (PDF, CSV, etc). | * 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. - **reportType**: 'default' - **generatedAt**: new Date() - **reportUrl**: 'default' ### Constant Properties `reportType` `filterParams` `generatedAt` `reportUrl` 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 `reportType` `generatedAt` 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 `reportType` `generatedAt` 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. --- ## Business APIs ### Business API Design Specification - `Create Adminissue` # Business API Design Specification - `Create Adminissue` 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 `createAdminIssue` 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 `createAdminIssue` Business API is designed to handle a `create` operation on the `AdminIssue` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Student or tutor files a new complaint/issue. Admin receives for review/investigation. Only admins can update or alter status; creator can get their own. ## 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 `adminissue-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 `createAdminIssue` Business API includes a REST controller that can be triggered via the following route: `/v1/adminissues` 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 `createAdminIssue` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAdminIssue` Business API has 9 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminIssueId` | `ID` | `No` | `-` | `body` | `adminIssueId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `reportedBy` | `ID` | `Yes` | `-` | `body` | `reportedBy` | | **Description:** | User who filed the issue (student or tutor). | | | | | | | | | | | | | `reportedUserId` | `ID` | `No` | `-` | `body` | `reportedUserId` | | **Description:** | (Optional) User being complained about | | | | | | | | | | | | | `coursePackId` | `ID` | `No` | `-` | `body` | `coursePackId` | | **Description:** | (Optional) ID of the related coursePack, if content/pack is complained about | | | | | | | | | | | | | `description` | `Text` | `Yes` | `-` | `body` | `description` | | **Description:** | Long text/body of the complaint/issue. | | | | | | | | | | | | | `issueType` | `Enum` | `Yes` | `-` | `body` | `issueType` | | **Description:** | Type of complaint (user, content, or other). | | | | | | | | | | | | | `status` | `Enum` | `Yes` | `-` | `body` | `status` | | **Description:** | Issue investigation status (open/investigating/resolved/dismissed). | | | | | | | | | | | | | `adminNote` | `String` | `No` | `-` | `body` | `adminNote` | | **Description:** | Internal/admin note for progress or findings (not visible to original user). | | | | | | | | | | | | | `resolution` | `Enum` | `No` | `-` | `body` | `resolution` | | **Description:** | Resolution outcome chosen by admin when closing the issue. | | | | | | | | | | | | ### 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 `createAdminIssue` 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: `[user, student, tutor, 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.adminIssueId, reportedBy: this.reportedBy, reportedUserId: this.reportedUserId, coursePackId: this.coursePackId, description: this.description, issueType: this.issueType, status: this.status, adminNote: this.adminNote, resolution: this.resolution, 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 `createAdminIssue` api has got 8 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportedBy | ID | true | request.body?.["reportedBy"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | true | request.body?.["description"] | | issueType | Enum | true | request.body?.["issueType"] | | status | Enum | true | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/adminissues** ```js axios({ method: 'POST', url: '/v1/adminissues', data: { reportedBy:"ID", reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"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 **`adminIssue`** 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": "adminIssue", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Adminissue` # Business API Design Specification - `Update Adminissue` 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 `updateAdminIssue` 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 `updateAdminIssue` Business API is designed to handle a `update` operation on the `AdminIssue` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin investigates/updates an issue: change status, add internal note, resolve/dismiss. Strictly 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 `adminissue-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 `updateAdminIssue` Business API includes a REST controller that can be triggered via the following route: `/v1/adminissues/:adminIssueId` 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 `updateAdminIssue` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateAdminIssue` 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. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminIssueId` | `ID` | `Yes` | `-` | `urlpath` | `adminIssueId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `reportedUserId` | `ID` | `No` | `-` | `body` | `reportedUserId` | | **Description:** | (Optional) User being complained about | | | | | | | | | | | | | `coursePackId` | `ID` | `No` | `-` | `body` | `coursePackId` | | **Description:** | (Optional) ID of the related coursePack, if content/pack is complained about | | | | | | | | | | | | | `description` | `Text` | `No` | `-` | `body` | `description` | | **Description:** | Long text/body of the complaint/issue. | | | | | | | | | | | | | `issueType` | `Enum` | `No` | `-` | `body` | `issueType` | | **Description:** | Type of complaint (user, content, or other). | | | | | | | | | | | | | `status` | `Enum` | `No` | `-` | `body` | `status` | | **Description:** | Issue investigation status (open/investigating/resolved/dismissed). | | | | | | | | | | | | | `adminNote` | `String` | `No` | `-` | `body` | `adminNote` | | **Description:** | Internal/admin note for progress or findings (not visible to original user). | | | | | | | | | | | | | `resolution` | `Enum` | `No` | `-` | `body` | `resolution` | | **Description:** | Resolution outcome chosen by admin when closing the issue. | | | | | | | | | | | | ### 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 `updateAdminIssue` 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]` --- ## 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.adminIssueId},{isActive:true}]}), {"path":"services[4].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 { reportedUserId: this.reportedUserId, coursePackId: this.coursePackId, description: this.description, issueType: this.issueType, status: this.status, adminNote: this.adminNote, resolution: this.resolution, } ``` ## 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] Action : fetchReporterUser **Action Type**: `FetchObjectAction` Fetch reporter user for notification email ```js class Api { async fetchReporterUser() { // Fetch Object on childObject user const userQuery = { $and: [ { id: runMScript(() => this.data.reportedBy, { path: "services[4].businessLogic[1].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("user"); const data = await elasticIndex.getOne(scriptQuery); return data ? { fullname: data["fullname"], email: data["email"], } : null; } } ``` --- ### [12] Action : buildReporterMessage **Action Type**: `AddToContextAction` ```js class Api { async buildReporterMessage() { try { this["reporterMessage"] = runMScript( () => this.status === "dismissed" ? "Your reported issue has been reviewed and dismissed." + (this.adminNote ? " Note: " + this.adminNote : "") : "Your reported issue has been reviewed and resolved." + (this.adminNote ? " Note: " + this.adminNote : ""), { path: "services[4].businessLogic[1].actions.addToContextActions[0].context[0].contextValue", }, ); this["reporterSeverity"] = runMScript( () => (this.status === "dismissed" ? "info" : "warning"), { path: "services[4].businessLogic[1].actions.addToContextActions[0].context[1].contextValue", }, ); return true; } catch (error) { console.error("AddToContextAction error:", error); throw error; } } } ``` --- ### [13] Action : notifyReporterViaChat **Action Type**: `InterserviceCallAction` ```js class Api { async notifyReporterViaChat() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["targetUserId"] = runMScript(() => this.reportedBy, { path: "services[4].businessLogic[1].actions.interserviceCallActions[0].apiParameters[0].value", }); bodyParams["targetUserRole"] = runMScript(() => "student", { path: "services[4].businessLogic[1].actions.interserviceCallActions[0].apiParameters[1].value", }); bodyParams["messageContent"] = runMScript(() => this.reporterMessage, { path: "services[4].businessLogic[1].actions.interserviceCallActions[0].apiParameters[2].value", }); bodyParams["resolutionType"] = runMScript( () => this.resolution || this.status, { path: "services[4].businessLogic[1].actions.interserviceCallActions[0].apiParameters[3].value", }, ); bodyParams["complaintId"] = runMScript(() => this.id, { path: "services[4].businessLogic[1].actions.interserviceCallActions[0].apiParameters[4].value", }); bodyParams["severity"] = runMScript(() => this.reporterSeverity, { path: "services[4].businessLogic[1].actions.interserviceCallActions[0].apiParameters[5].value", }); const resp = await InterService.callMessagingSendSystemMessage({ body: bodyParams, }); return resp?.content ?? resp; } } ``` --- ### [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 `updateAdminIssue` api has got 8 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | false | request.body?.["description"] | | issueType | Enum | false | request.body?.["issueType"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/adminissues/:adminIssueId** ```js axios({ method: 'PATCH', url: `/v1/adminissues/${adminIssueId}`, data: { reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"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 **`adminIssue`** 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": "adminIssue", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "reporterUser": { "email": "String", "fullname": "String" } } ``` --- ### Business API Design Specification - `Get Adminissue` # Business API Design Specification - `Get Adminissue` 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 `getAdminIssue` 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 `getAdminIssue` Business API is designed to handle a `get` operation on the `AdminIssue` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Fetches a single issue by ID. Admins may get any; creator may get/view their own for status updates. ## 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 `adminissue-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 `getAdminIssue` Business API includes a REST controller that can be triggered via the following route: `/v1/adminissues/:adminIssueId` 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 `getAdminIssue` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAdminIssue` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminIssueId` | `ID` | `Yes` | `-` | `urlpath` | `adminIssueId` | | **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 `getAdminIssue` 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.", `id`,`reportedBy`,`reportedUserId`,`coursePackId`,`description`,`issueType`,`status`,`adminNote` ## 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.adminIssueId},{isActive:true}]}), {"path":"services[4].businessLogic[2].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 `getAdminIssue` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/adminissues/:adminIssueId** ```js axios({ method: 'GET', url: `/v1/adminissues/${adminIssueId}`, 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 **`adminIssue`** 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": "adminIssue", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminIssue": { "reporter": { "email": "String", "fullname": "String" }, "reportedUser": { "email": "String", "fullname": "String" }, "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` --- ### Business API Design Specification - `List Adminissues` # Business API Design Specification - `List Adminissues` 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 `listAdminIssues` 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 `listAdminIssues` Business API is designed to handle a `list` operation on the `AdminIssue` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description List issues with filters for admin dashboard: by status/type/target. 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 `adminissues-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 `listAdminIssues` Business API includes a REST controller that can be triggered via the following route: `/v1/adminissues` 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 `listAdminIssues` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAdminIssues` 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 `listAdminIssues` 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.", `id`,`reportedBy`,`reportedUserId`,`coursePackId`,`description`,`issueType`,`status`,`adminNote`,`resolution`,`createdAt` ## 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[4].businessLogic[3].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 `listAdminIssues` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/adminissues** ```js axios({ method: 'GET', url: '/v1/adminissues', 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 **`adminIssues`** 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": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reporter": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "reportedUser": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Adminmoderationaction` # Business API Design Specification - `Create Adminmoderationaction` 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 `createAdminModerationAction` 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 `createAdminModerationAction` Business API is designed to handle a `create` operation on the `AdminModerationAction` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Admin records a moderation action against a user/object. Admin only. Write-side audit log for all moderator events. ## 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 `adminmoderationaction-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 `createAdminModerationAction` Business API includes a REST controller that can be triggered via the following route: `/v1/adminmoderationactions` 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 `createAdminModerationAction` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAdminModerationAction` 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. ### Regular Parameters | Name | Type | Required | Default | Location | Data Path | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminModerationActionId` | `ID` | `No` | `-` | `body` | `adminModerationActionId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `adminId` | `ID` | `Yes` | `-` | `body` | `adminId` | | **Description:** | Admin performing moderation action. | | | | | | | | | | | | | `targetType` | `Enum` | `Yes` | `-` | `body` | `targetType` | | **Description:** | Moderation target type (user/coursePack/profile/material). | | | | | | | | | | | | | `targetId` | `ID` | `Yes` | `-` | `body` | `targetId` | | **Description:** | ID of moderation target object (userId, coursePackId, etc). | | | | | | | | | | | | | `actionType` | `Enum` | `Yes` | `-` | `body` | `actionType` | | **Description:** | Type of moderation action (suspend, ban, edit, remove, approve, warn). | | | | | | | | | | | | | `actionReason` | `String` | `Yes` | `-` | `body` | `actionReason` | | **Description:** | Reason for moderation action, as recorded by the admin. | | | | | | | | | | | | | `actionDate` | `Date` | `Yes` | `-` | `body` | `actionDate` | | **Description:** | Datetime when the action took place. | | | | | | | | | | | | | `targetUserId` | `ID` | `Yes` | `-` | `body` | `targetUserId` | | **Description:** | UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the 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 `createAdminModerationAction` 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** *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.adminModerationActionId, adminId: this.adminId, targetType: this.targetType, targetId: this.targetId, actionType: this.actionType, actionReason: this.actionReason, actionDate: this.actionDate, targetUserId: this.targetUserId, 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] Action : fetchTargetUser **Action Type**: `FetchObjectAction` Fetch the target user to include their email in the API output for notifications ```js class Api { async fetchTargetUser() { // Fetch Object on childObject user const userQuery = { $and: [ { id: runMScript(() => this.targetUserId, { path: "services[4].businessLogic[4].actions.fetchObjectActions[0].matchValue", }), }, { isActive: true }, ], }; const { convertUserQueryToElasticQuery } = require("common"); const scriptQuery = convertUserQueryToElasticQuery(userQuery); const elasticIndex = new ElasticIndexer("user"); const data = await elasticIndex.getOne(scriptQuery); return data ? { fullname: data["fullname"], email: data["email"], } : null; } } ``` --- ### [9] Action : resolveTargetRole **Action Type**: `AddToContextAction` ```js class Api { async resolveTargetRole() { try { this["resolvedTargetUserRole"] = runMScript( () => (this.targetType === "user" ? "student" : "tutor"), { path: "services[4].businessLogic[4].actions.addToContextActions[0].context[0].contextValue", }, ); this["resolvedTargetUserId"] = runMScript( () => (this.targetType === "user" ? this.targetId : null), { path: "services[4].businessLogic[4].actions.addToContextActions[0].context[1].contextValue", }, ); this["severityLevel"] = runMScript( () => ["suspend", "ban"].includes(this.actionType) ? "critical" : this.actionType === "warn" ? "warning" : "info", { path: "services[4].businessLogic[4].actions.addToContextActions[0].context[2].contextValue", }, ); return true; } catch (error) { console.error("AddToContextAction error:", error); throw error; } } } ``` --- ### [10] Action : sendWarningToUser **Action Type**: `InterserviceCallAction` ```js class Api { async sendWarningToUser() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["targetUserId"] = runMScript(() => this.targetId, { path: "services[4].businessLogic[4].actions.interserviceCallActions[0].apiParameters[0].value", }); bodyParams["targetUserRole"] = runMScript( () => this.resolvedTargetUserRole, { path: "services[4].businessLogic[4].actions.interserviceCallActions[0].apiParameters[1].value", }, ); bodyParams["messageContent"] = runMScript(() => this.actionReason, { path: "services[4].businessLogic[4].actions.interserviceCallActions[0].apiParameters[2].value", }); bodyParams["resolutionType"] = runMScript(() => this.actionType, { path: "services[4].businessLogic[4].actions.interserviceCallActions[0].apiParameters[3].value", }); bodyParams["severity"] = runMScript(() => this.severityLevel, { path: "services[4].businessLogic[4].actions.interserviceCallActions[0].apiParameters[4].value", }); const resp = await InterService.callMessagingSendSystemMessage({ body: bodyParams, }); return resp?.content ?? resp; } } ``` --- ### [11] Action : sendWarningToTutorForContent **Action Type**: `InterserviceCallAction` ```js class Api { async sendWarningToTutorForContent() { const { InterService } = require("serviceCommon"); const bodyParams = {}; bodyParams["targetUserId"] = runMScript(() => this.targetId, { path: "services[4].businessLogic[4].actions.interserviceCallActions[1].apiParameters[0].value", }); bodyParams["targetUserRole"] = runMScript(() => "tutor", { path: "services[4].businessLogic[4].actions.interserviceCallActions[1].apiParameters[1].value", }); bodyParams["messageContent"] = runMScript(() => this.actionReason, { path: "services[4].businessLogic[4].actions.interserviceCallActions[1].apiParameters[2].value", }); bodyParams["resolutionType"] = runMScript(() => this.actionType, { path: "services[4].businessLogic[4].actions.interserviceCallActions[1].apiParameters[3].value", }); bodyParams["severity"] = runMScript(() => this.severityLevel, { path: "services[4].businessLogic[4].actions.interserviceCallActions[1].apiParameters[4].value", }); const resp = await InterService.callMessagingSendSystemMessage({ body: bodyParams, }); return resp?.content ?? resp; } } ``` --- ### [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 `createAdminModerationAction` api has got 7 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminId | ID | true | request.body?.["adminId"] | | targetType | Enum | true | request.body?.["targetType"] | | targetId | ID | true | request.body?.["targetId"] | | actionType | Enum | true | request.body?.["actionType"] | | actionReason | String | true | request.body?.["actionReason"] | | actionDate | Date | true | request.body?.["actionDate"] | | targetUserId | ID | true | request.body?.["targetUserId"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/adminmoderationactions** ```js axios({ method: 'POST', url: '/v1/adminmoderationactions', data: { adminId:"ID", targetType:"Enum", targetId:"ID", actionType:"Enum", actionReason:"String", actionDate:"Date", targetUserId:"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 **`adminModerationAction`** 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": "adminModerationAction", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "id": "ID", "adminId": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "actionType": "Enum", "actionType_idx": "Integer", "actionReason": "String", "actionDate": "Date", "targetUserId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "targetUser": { "email": "String", "fullname": "String" } } ``` --- ### Business API Design Specification - `Get Adminmoderationaction` # Business API Design Specification - `Get Adminmoderationaction` 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 `getAdminModerationAction` 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 `getAdminModerationAction` Business API is designed to handle a `get` operation on the `AdminModerationAction` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get one moderation action. 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 `adminmoderationaction-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 `getAdminModerationAction` Business API includes a REST controller that can be triggered via the following route: `/v1/adminmoderationactions/:adminModerationActionId` 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 `getAdminModerationAction` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAdminModerationAction` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminModerationActionId` | `ID` | `Yes` | `-` | `urlpath` | `adminModerationActionId` | | **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 `getAdminModerationAction` 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.", `id`,`adminId`,`targetType`,`targetId`,`actionType`,`actionReason`,`actionDate` ## 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.adminModerationActionId},{isActive:true}]}), {"path":"services[4].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 `getAdminModerationAction` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminModerationActionId | ID | true | request.params?.["adminModerationActionId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/adminmoderationactions/:adminModerationActionId** ```js axios({ method: 'GET', url: `/v1/adminmoderationactions/${adminModerationActionId}`, 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 **`adminModerationAction`** 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": "adminModerationAction", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "admin": { "email": "String", "fullname": "String" }, "isActive": true } } ``` --- ### Business API Design Specification - `List Adminmoderationactions` # Business API Design Specification - `List Adminmoderationactions` 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 `listAdminModerationActions` 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 `listAdminModerationActions` Business API is designed to handle a `list` operation on the `AdminModerationAction` 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 admin moderation actions, filterable by actionType/targetType/date. For admin dashboard audit log. ## 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 `adminmoderationactions-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 `listAdminModerationActions` Business API includes a REST controller that can be triggered via the following route: `/v1/adminmoderationactions` 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 `listAdminModerationActions` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAdminModerationActions` 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 `listAdminModerationActions` 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.", `id`,`adminId`,`targetType`,`targetId`,`actionType`,`actionReason`,`actionDate` ## 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[4].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). [ actionDate 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 `listAdminModerationActions` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/adminmoderationactions** ```js axios({ method: 'GET', url: '/v1/adminmoderationactions', 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 **`adminModerationActions`** 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": "adminModerationActions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminModerationActions": [ { "admin": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Create Adminanalyticsreport` # Business API Design Specification - `Create Adminanalyticsreport` 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 `createAdminAnalyticsReport` 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 `createAdminAnalyticsReport` Business API is designed to handle a `create` operation on the `AdminAnalyticsReport` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Create record for a new analytics report (usually admin-triggered on dashboard, actual report process may be async via edge controller in future). Admin-only; records metadata and download URL of available report. ## 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 `adminanalyticsreport-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 `createAdminAnalyticsReport` Business API includes a REST controller that can be triggered via the following route: `/v1/adminanalyticsreports` 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 `createAdminAnalyticsReport` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createAdminAnalyticsReport` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminAnalyticsReportId` | `ID` | `No` | `-` | `body` | `adminAnalyticsReportId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `reportType` | `String` | `Yes` | `-` | `body` | `reportType` | | **Description:** | Type of the analytics report (enrollments, revenue, complaints, etc). | | | | | | | | | | | | | `filterParams` | `String` | `No` | `-` | `body` | `filterParams` | | **Description:** | Filter params as stringified JSON for reporting input. | | | | | | | | | | | | | `generatedAt` | `Date` | `Yes` | `-` | `body` | `generatedAt` | | **Description:** | Date/time report was generated. | | | | | | | | | | | | | `reportUrl` | `String` | `Yes` | `-` | `body` | `reportUrl` | | **Description:** | Accessible URL where generated report is stored (PDF, CSV, etc). | | | | | | | | | | | | ### 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 `createAdminAnalyticsReport` 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** *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.adminAnalyticsReportId, reportType: this.reportType, filterParams: this.filterParams, generatedAt: this.generatedAt, reportUrl: this.reportUrl, 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 `createAdminAnalyticsReport` api has got 4 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportType | String | true | request.body?.["reportType"] | | filterParams | String | false | request.body?.["filterParams"] | | generatedAt | Date | true | request.body?.["generatedAt"] | | reportUrl | String | true | request.body?.["reportUrl"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/adminanalyticsreports** ```js axios({ method: 'POST', url: '/v1/adminanalyticsreports', data: { reportType:"String", filterParams:"String", generatedAt:"Date", reportUrl:"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 **`adminAnalyticsReport`** 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": "adminAnalyticsReport", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "id": "ID", "reportType": "String", "filterParams": "String", "generatedAt": "Date", "reportUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Adminanalyticsreport` # Business API Design Specification - `Get Adminanalyticsreport` 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 `getAdminAnalyticsReport` 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 `getAdminAnalyticsReport` Business API is designed to handle a `get` operation on the `AdminAnalyticsReport` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Get one analytics report record for download from admin dashboard. 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 `adminanalyticsreport-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 `getAdminAnalyticsReport` Business API includes a REST controller that can be triggered via the following route: `/v1/adminanalyticsreports/:adminAnalyticsReportId` 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 `getAdminAnalyticsReport` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getAdminAnalyticsReport` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `adminAnalyticsReportId` | `ID` | `Yes` | `-` | `urlpath` | `adminAnalyticsReportId` | | **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 `getAdminAnalyticsReport` 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.", `id`,`reportType`,`filterParams`,`generatedAt`,`reportUrl` ## 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.adminAnalyticsReportId},{isActive:true}]}), {"path":"services[4].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 `getAdminAnalyticsReport` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminAnalyticsReportId | ID | true | request.params?.["adminAnalyticsReportId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/adminanalyticsreports/:adminAnalyticsReportId** ```js axios({ method: 'GET', url: `/v1/adminanalyticsreports/${adminAnalyticsReportId}`, 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 **`adminAnalyticsReport`** 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": "adminAnalyticsReport", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "isActive": true } } ``` --- ### Business API Design Specification - `List Adminanalyticsreports` # Business API Design Specification - `List Adminanalyticsreports` 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 `listAdminAnalyticsReports` 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 `listAdminAnalyticsReports` Business API is designed to handle a `list` operation on the `AdminAnalyticsReport` 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 analytics reports for admin dashboard access (download/view). 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 `adminanalyticsreports-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 `listAdminAnalyticsReports` Business API includes a REST controller that can be triggered via the following route: `/v1/adminanalyticsreports` 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 `listAdminAnalyticsReports` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listAdminAnalyticsReports` 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 `listAdminAnalyticsReports` 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.", `id`,`reportType`,`filterParams`,`generatedAt`,`reportUrl` ## 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[4].businessLogic[9].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). [ generatedAt 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 `listAdminAnalyticsReports` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/adminanalyticsreports** ```js axios({ method: 'GET', url: '/v1/adminanalyticsreports', 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 **`adminAnalyticsReports`** 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": "adminAnalyticsReports", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminAnalyticsReports": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `List Myissues` # Business API Design Specification - `List Myissues` 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 `listMyIssues` 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 `listMyIssues` Business API is designed to handle a `list` operation on the `AdminIssue` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Students and tutors list their own reported issues. Ownership check ensures users only see their own reports. ## 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 `listMyIssues` Business API includes a REST controller that can be triggered via the following route: `/v1/myissues` 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 `listMyIssues` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listMyIssues` 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 `listMyIssues` 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: `[user, student, tutor, 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.", `id`,`reportedBy`,`reportedUserId`,`coursePackId`,`description`,`issueType`,`status`,`createdAt` ## 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. ```js // Addtional Clause Name : filterByReporter // condition doWhen // No doWhen condtion defined // condition excludeWhen // No excludeWhen condtion defined // clause object { reportedBy: { $eq: this.session.userId } } ``` **Actual Where Clause** This where clause is built using whereClause configuration (if set) and default business logic. ```js runMScript(() => ({$and:[{ reportedBy: { $eq: this.session.userId } },{isActive:true}]}), {"path":"services[4].businessLogic[10].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 `listMyIssues` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/myissues** ```js axios({ method: 'GET', url: '/v1/myissues', 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 **`adminIssues`** 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": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reportedUser": [ { "email": "String", "fullname": "String" }, {}, {} ], "coursePack": [ { "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- # Messaging Service ## Service Design Specification # Service Design Specification **tutorhub-messaging-service** documentation **Version:** `1.0.15` ## Scope This document provides a structured architectural overview of the `messaging` 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. ## `Messaging` Service Settings Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. ### Service Overview This service is configured to listen for HTTP requests on port `3000`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-messaging-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/messaging-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/messaging-api` * **Production:** `https://tutorhub.mindbricks.co/messaging-api` ### Authentication & Security - **Login Required**: Yes This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context. ### Service Data Objects The service uses a **PostgreSQL** database for data storage, with the database name set to `tutorhub-messaging-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 | |-------------|-------------|---------------| | `conversation` | Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). | accessPrivate | | `chatMessage` | Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. | accessPrivate | | `chatModeration` | Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. | accessPrivate | ## conversation Data Object ### Object Overview **Description:** Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **unique_conversation_pair**: [participantA, participantB, enrollmentId] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `conversationType` | String | Yes | Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. | | `participantA` | ID | Yes | First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. | | `participantB` | ID | Yes | Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. | | `enrollmentId` | ID | No | FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. | | `lastMessageAt` | Date | No | Timestamp of the most recent message. Used for sorting conversations in inbox. | | `lastMessagePreview` | String | No | Truncated preview of last message content. Shown in conversation list. | | `status` | String | Yes | Conversation status: active or closed. | | `participantAName` | String | No | Cached display name of participant A for quick rendering in conversation list. | | `participantBName` | String | No | Cached display name of participant B for quick rendering in conversation list. | | `courseTitle` | String | No | Cached course pack title for display. Set on conversation creation for studentTutor type. | * 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. - **conversationType**: 'default' - **participantA**: '00000000-0000-0000-0000-000000000000' - **participantB**: '00000000-0000-0000-0000-000000000000' - **status**: active ### 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 `active` ### Constant Properties `conversationType` `participantA` `participantB` `enrollmentId` 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 `conversationType` `participantA` `participantB` `enrollmentId` `lastMessageAt` `lastMessagePreview` `status` `participantAName` `participantBName` `courseTitle` 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. - **conversationType**: [studentTutor, adminStudent, adminTutor] - **status**: [active, closed] ### Elastic Search Indexing `conversationType` `participantA` `participantB` `enrollmentId` `lastMessageAt` `status` `participantAName` `participantBName` `courseTitle` 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 `conversationType` `participantA` `participantB` `enrollmentId` `lastMessageAt` `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 `participantA` `participantB` `enrollmentId` 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. - **participantA**: 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 - **participantB**: 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 - **enrollmentId**: ID Relation to `enrollment`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: No ## chatMessage Data Object ### Object Overview **Description:** Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. 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 | |----------|------|----------|-------------| | `roomId` | ID | Yes | Reference to the room this message belongs to | | `senderId` | ID | No | Reference to the user who sent this message | | `senderName` | String | No | Display name of the sender (denormalized from user profile at send time) | | `senderAvatar` | String | No | Avatar URL of the sender (denormalized from user profile at send time) | | `messageType` | Enum | Yes | Content type discriminator for this message | | `content` | Object | Yes | Type-specific content payload (structure depends on messageType) | | `timestamp` | | No | Message creation time | | `status` | Enum | No | Message moderation status | | `replyTo` | Object | No | Reply thread reference { id, preview } | * 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. - **roomId**: '00000000-0000-0000-0000-000000000000' - **messageType**: "text" - **content**: {} - **timestamp**: now() - **status**: approved ### Constant Properties `roomId` `senderId` `senderName` `senderAvatar` `messageType` `timestamp` `replyTo` 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 `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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. - **messageType**: [text, image, document, system, warning] - **status**: [pending, approved, rejected] ### Elastic Search Indexing `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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 `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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 `roomId` 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 `senderId` 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. - **senderId**: ID property will be mapped to the session parameter `userId`. ### Filter Properties `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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. - **roomId**: ID has a filter named `roomId` - **senderId**: ID has a filter named `senderId` - **senderName**: String has a filter named `senderName` - **senderAvatar**: String has a filter named `senderAvatar` - **messageType**: Enum has a filter named `messageType` - **content**: Object has a filter named `content` - **timestamp**: has a filter named `timestamp` - **status**: Enum has a filter named `status` - **replyTo**: Object has a filter named `replyTo` ## chatModeration Data Object ### Object Overview **Description:** Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. 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 | |----------|------|----------|-------------| | `roomId` | ID | Yes | Reference to the room where the moderation action applies | | `userId` | ID | Yes | The user who is blocked or silenced | | `action` | Enum | Yes | Moderation action type | | `reason` | Text | No | Optional reason for the moderation action | | `duration` | Integer | No | Duration in seconds. 0 means permanent | | `expiresAt` | | No | Expiry timestamp. Null means permanent | | `issuedBy` | ID | No | The moderator who issued the action | * 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. - **roomId**: '00000000-0000-0000-0000-000000000000' - **userId**: '00000000-0000-0000-0000-000000000000' - **action**: "blocked" - **duration**: 0 ### Constant Properties `roomId` `userId` `action` `duration` `expiresAt` `issuedBy` 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 `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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**: [blocked, silenced] ### Elastic Search Indexing `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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 `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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 `roomId` `userId` 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 `roomId` 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. - **roomId**: ID Relation to `conversation`.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 `issuedBy` 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. - **issuedBy**: ID property will be mapped to the session parameter `userId`. ### Filter Properties `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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. - **roomId**: ID has a filter named `roomId` - **userId**: ID has a filter named `userId` - **action**: Enum has a filter named `action` - **reason**: Text has a filter named `reason` - **duration**: Integer has a filter named `duration` - **expiresAt**: has a filter named `expiresAt` - **issuedBy**: ID has a filter named `issuedBy` ## Business Logic messaging has got 8 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter. * [Create Conversation](/document/businessLogic/createconversation) * [Get Conversation](/document/businessLogic/getconversation) * [List Myconversations](/document/businessLogic/listmyconversations) * [Send Systemmessage](/document/businessLogic/sendsystemmessage) * [List Chatmessages](/document/businessLogic/listchatmessages) * [Get Chatmessage](/document/businessLogic/getchatmessage) * [Delete Chatmessage](/document/businessLogic/deletechatmessage) * [Update Chatmessage](/document/businessLogic/updatechatmessage) ## Realtime Hubs messaging has 1 Realtime Hub configured. Each hub provides bidirectional communication powered by Socket.IO with room-based messaging, built-in and custom message types, and auto-generated REST endpoints. | Hub Name | Namespace | Room DataObject | Roles | |----------|-----------|----------------|-------| | `chat` | `/hub/chat` | `conversation` | member, viewer | For detailed documentation on each hub, refer to: * [chat](/document/realtimeHubs/chat) --- *This document was generated from the service architecture definition and should be kept in sync with implementation changes.* --- ## REST API GUIDE # REST API GUIDE ## tutorhub-messaging-service **Version:** `1.0.15` Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. ## 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 Messaging Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Messaging Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Messaging Service via HTTP requests for purposes such as creating, updating, deleting and querying Messaging 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 Messaging 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 Messaging 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 | tutorhub-access-token| | Cookie | tutorhub-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 Messaging 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 Messaging service. This service is configured to listen for HTTP requests on port `3000`, 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://tutorhub.prw.mindbricks.com/messaging-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/messaging-api` * **Production:** `https://tutorhub.mindbricks.co/messaging-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 Messaging 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 `Messaging` 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 `Messaging` 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 `Messaging` 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 Messaging 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. ### Conversation resource *Resource Definition* : Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). *Conversation Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **conversationType** | String | | | *Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions.* | | **participantA** | ID | | | *First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin.* | | **participantB** | ID | | | *Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor.* | | **enrollmentId** | ID | | | *FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context.* | | **lastMessageAt** | Date | | | *Timestamp of the most recent message. Used for sorting conversations in inbox.* | | **lastMessagePreview** | String | | | *Truncated preview of last message content. Shown in conversation list.* | | **status** | String | | | *Conversation status: active or closed.* | | **participantAName** | String | | | *Cached display name of participant A for quick rendering in conversation list.* | | **participantBName** | String | | | *Cached display name of participant B for quick rendering in conversation list.* | | **courseTitle** | String | | | *Cached course pack title for display. Set on conversation creation for studentTutor type.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### conversationType Enum Property *Property Definition* : Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **studentTutor** | `"studentTutor""` | 0 | | **adminStudent** | `"adminStudent""` | 1 | | **adminTutor** | `"adminTutor""` | 2 | ##### status Enum Property *Property Definition* : Conversation status: active or closed.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **closed** | `"closed""` | 1 | ### ChatMessage resource *Resource Definition* : Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. *ChatMessage Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **roomId** | ID | | | *Reference to the room this message belongs to* | | **senderId** | ID | | | *Reference to the user who sent this message* | | **senderName** | String | | | *Display name of the sender (denormalized from user profile at send time)* | | **senderAvatar** | String | | | *Avatar URL of the sender (denormalized from user profile at send time)* | | **messageType** | Enum | | | *Content type discriminator for this message* | | **content** | Object | | | *Type-specific content payload (structure depends on messageType)* | | **timestamp** | | | | *Message creation time* | | **status** | Enum | | | *Message moderation status* | | **replyTo** | Object | | | *Reply thread reference { id, preview }* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### messageType Enum Property *Property Definition* : Content type discriminator for this message*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **text** | `"text""` | 0 | | **image** | `"image""` | 1 | | **document** | `"document""` | 2 | | **system** | `"system""` | 3 | | **warning** | `"warning""` | 4 | ##### status Enum Property *Property Definition* : Message moderation status*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ### ChatModeration resource *Resource Definition* : Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. *ChatModeration Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **roomId** | ID | | | *Reference to the room where the moderation action applies* | | **userId** | ID | | | *The user who is blocked or silenced* | | **action** | Enum | | | *Moderation action type* | | **reason** | Text | | | *Optional reason for the moderation action* | | **duration** | Integer | | | *Duration in seconds. 0 means permanent* | | **expiresAt** | | | | *Expiry timestamp. Null means permanent* | | **issuedBy** | ID | | | *The moderator who issued the action* | #### 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 type*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **blocked** | `"blocked""` | 0 | | **silenced** | `"silenced""` | 1 | ## Business Api ### `Create Conversation` API **[Default create API]** — This is the designated default `create` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Creates a new conversation between two participants. For studentTutor type, requires valid enrollment. For adminStudent/adminTutor, only admin can create. **API Frontend Description By The Backend Architect** ## Create Conversation - Tutors/students can create studentTutor conversations. - Only admin can create adminStudent or adminTutor conversations. - Before creating, check if conversation already exists between the two participants of same type. **Rest Route** The `createConversation` API REST controller can be triggered via the following route: `/v1/conversations` **Rest Request Parameters** The `createConversation` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationType | String | true | request.body?.["conversationType"] | | participantA | ID | true | request.body?.["participantA"] | | participantB | ID | true | request.body?.["participantB"] | | enrollmentId | ID | false | request.body?.["enrollmentId"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | | lastMessagePreview | String | false | request.body?.["lastMessagePreview"] | | participantAName | String | false | request.body?.["participantAName"] | | participantBName | String | false | request.body?.["participantBName"] | | courseTitle | String | false | request.body?.["courseTitle"] | **conversationType** : Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. **participantA** : First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. **participantB** : Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. **enrollmentId** : FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. **lastMessageAt** : Timestamp of the most recent message. Used for sorting conversations in inbox. **lastMessagePreview** : Truncated preview of last message content. Shown in conversation list. **participantAName** : Cached display name of participant A for quick rendering in conversation list. **participantBName** : Cached display name of participant B for quick rendering in conversation list. **courseTitle** : Cached course pack title for display. Set on conversation creation for studentTutor type. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/conversations** ```js axios({ method: 'POST', url: '/v1/conversations', data: { conversationType:"String", participantA:"ID", participantB:"ID", enrollmentId:"ID", lastMessageAt:"Date", lastMessagePreview:"String", participantAName:"String", participantBName:"String", courseTitle:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Conversation` API **[Default get API]** — This is the designated default `get` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single conversation by ID. Only participants or admin can view. **Rest Route** The `getConversation` API REST controller can be triggered via the following route: `/v1/conversations/:conversationId` **Rest Request Parameters** The `getConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | **conversationId** : 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/conversations/:conversationId** ```js axios({ method: 'GET', url: `/v1/conversations/${conversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" } } } ``` ### `List Myconversations` API **[Default list API]** — This is the designated default `list` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Lists all conversations where the current user is a participant. Sorted by lastMessageAt descending. **API Frontend Description By The Backend Architect** ## Inbox / Conversation List - Shows all conversations for the logged-in user sorted by most recent. - Show: other participant name, last message preview, timestamp, unread badge. - For adminStudent type show 'Admin Notice' label. For adminTutor show 'Admin' label. - Clicking opens the chat view. **Rest Route** The `listMyConversations` API REST controller can be triggered via the following route: `/v1/myconversations` **Rest Request Parameters** The `listMyConversations` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myconversations** ```js axios({ method: 'GET', url: '/v1/myconversations', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "conversations": [ { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Send Systemmessage` API Interservice API called by adminPanel for moderation warnings. Creates/finds admin conversation with target user and sends a warning message. M2M only. **API Frontend Description By The Backend Architect** This API is not called from frontend. It is an interservice endpoint for adminPanel to deliver moderation warnings as chat messages. **Rest Route** The `sendSystemMessage` API REST controller can be triggered via the following route: `/v1/sendsystemmessage` **Rest Request Parameters** The `sendSystemMessage` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | targetUserId | ID | true | request.body?.["targetUserId"] | | targetUserRole | String | true | request.body?.["targetUserRole"] | | messageContent | Text | true | request.body?.["messageContent"] | | resolutionType | String | false | request.body?.["resolutionType"] | | complaintId | ID | false | request.body?.["complaintId"] | | severity | String | false | request.body?.["severity"] | **targetUserId** : The userId of the user to send the warning to **targetUserRole** : Role of target: student or tutor. Determines conversation type **messageContent** : The warning message content **resolutionType** : Moderation resolution type: warn, requireEdit, removeCourse, suspend, ban **complaintId** : Reference to original complaint/issue ID **severity** : Warning severity: info, warning, critical **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/sendsystemmessage** ```js axios({ method: 'POST', url: '/v1/sendsystemmessage', data: { targetUserId:"ID", targetUserRole:"String", messageContent:"Text", resolutionType:"String", complaintId:"ID", severity:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "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 messages in a chat hub room. Accessible by admins and room participants. **Rest Route** The `listChatMessages` API REST controller can be triggered via the following route: `/v1/v1/chat-messages` **Rest Request Parameters** **Filter Parameters** The `listChatMessages` api supports 9 optional filter parameters for filtering list results: **roomId** (`ID`): Reference to the room this message belongs to - Single: `?roomId=` - Multiple: `?roomId=&roomId=` - Null: `?roomId=null` **senderId** (`ID`): Reference to the user who sent this message - Single: `?senderId=` - Multiple: `?senderId=&senderId=` - Null: `?senderId=null` **senderName** (`String`): Display name of the sender (denormalized from user profile at send time) - Single (partial match, case-insensitive): `?senderName=` - Multiple: `?senderName=&senderName=` - Null: `?senderName=null` **senderAvatar** (`String`): Avatar URL of the sender (denormalized from user profile at send time) - Single (partial match, case-insensitive): `?senderAvatar=` - Multiple: `?senderAvatar=&senderAvatar=` - Null: `?senderAvatar=null` **messageType** (`Enum`): Content type discriminator for this message - Single: `?messageType=` (case-insensitive) - Multiple: `?messageType=&messageType=` - Null: `?messageType=null` **content** (`Object`): Type-specific content payload (structure depends on messageType) - Single: `?content=` - Multiple: `?content=&content=` - Null: `?content=null` **timestamp** (`String`): Message creation time - Single (partial match, case-insensitive): `?timestamp=` - Multiple: `?timestamp=×tamp=` - Null: `?timestamp=null` **status** (`Enum`): Message moderation status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **replyTo** (`Object`): Reply thread reference { id, preview } - Single: `?replyTo=` - Multiple: `?replyTo=&replyTo=` - Null: `?replyTo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages** ```js axios({ method: 'GET', url: '/v1/v1/chat-messages', data: { }, params: { // Filter parameters (see Filter Parameters section above) // roomId: '' // Filter by roomId // senderId: '' // Filter by senderId // senderName: '' // Filter by senderName // senderAvatar: '' // Filter by senderAvatar // messageType: '' // Filter by messageType // content: '' // Filter by content // timestamp: '' // Filter by timestamp // status: '' // Filter by status // replyTo: '' // Filter by replyTo } }); ``` **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", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `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 single chat hub message by ID. **Rest Route** The `getChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `getChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to query the required data object. **id** : This parameter will be used to select the data object that is queried **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages/:id** ```js axios({ method: 'GET', url: `/v1/v1/chat-messages/${id}`, 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", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Chatmessage` API **[Default delete API]** — This is the designated default `delete` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a chat hub message. Admins can delete any message; users can delete their own. **Rest Route** The `deleteChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `deleteChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to select the required data object that will be deleted **id** : This parameter will be used to select the data object that want to be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/v1/chat-messages/:id** ```js axios({ method: 'DELETE', url: `/v1/v1/chat-messages/${id}`, 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": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Chatmessage` API **[Default update API]** — This is the designated default `update` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a chat hub message content. Only the message sender or admins can edit. **Rest Route** The `updateChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `updateChatMessage` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | content | Object | false | request.body?.["content"] | | status | Enum | false | request.body?.["status"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to select the required data object that will be updated **content** : Type-specific content payload (structure depends on messageType) **status** : Message moderation status **id** : This parameter will be used to select the data object that want to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/v1/chat-messages/:id** ```js axios({ method: 'PATCH', url: `/v1/v1/chat-messages/${id}`, data: { content:"Object", status:"Enum", }, 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": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### 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 ## tutorhub-messaging-service Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. ## 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 `Messaging` Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the `Messaging` Service, offering an exclusive focus on event subscription mechanisms. **Intended Audience** This documentation is aimed at developers and integrators looking to monitor `Messaging` Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with `Messaging` 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 `Messaging` 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 conversation-created **Event topic**: `tutorhub-messaging-service-dbevent-conversation-created` This event is triggered upon the creation of a `conversation` 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","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent conversation-updated **Event topic**: `tutorhub-messaging-service-dbevent-conversation-updated` Activation of this event follows the update of a `conversation` data object. The payload contains the updated information under the `conversation` attribute, along with the original data prior to update, labeled as `old_conversation` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_conversation:{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, conversation:{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent conversation-deleted **Event topic**: `tutorhub-messaging-service-dbevent-conversation-deleted` This event announces the deletion of a `conversation` 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","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent chatMessage-created **Event topic**: `tutorhub-messaging-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","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent chatMessage-updated **Event topic**: `tutorhub-messaging-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","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, chatMessage:{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent chatMessage-deleted **Event topic**: `tutorhub-messaging-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","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent chatModeration-created **Event topic**: `tutorhub-messaging-service-dbevent-chatmoderation-created` This event is triggered upon the creation of a `chatModeration` 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","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## DbEvent chatModeration-updated **Event topic**: `tutorhub-messaging-service-dbevent-chatmoderation-updated` Activation of this event follows the update of a `chatModeration` data object. The payload contains the updated information under the `chatModeration` attribute, along with the original data prior to update, labeled as `old_chatModeration` and also you can find the old and new versions of updated-only portion of the data.. **Event payload**: ```json { old_chatModeration:{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, chatModeration:{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}, oldDataValues, newDataValues } ``` ## DbEvent chatModeration-deleted **Event topic**: `tutorhub-messaging-service-dbevent-chatmoderation-deleted` This event announces the deletion of a `chatModeration` 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","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false} ``` # ElasticSearch Index Events Within the `Messaging` 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 conversation-created **Event topic**: `elastic-index-tutorhub_conversation-created` **Event payload**: ```json {"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event conversation-updated **Event topic**: `elastic-index-tutorhub_conversation-created` **Event payload**: ```json {"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event conversation-deleted **Event topic**: `elastic-index-tutorhub_conversation-deleted` **Event payload**: ```json {"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event conversation-extended **Event topic**: `elastic-index-tutorhub_conversation-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 conversation-created **Event topic** : `tutorhub-messaging-service-conversation-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 `conversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`conversation`** 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":"conversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversation":{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event systemmessage-sent **Event topic** : `tutorhub-messaging-service-systemmessage-sent` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `conversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`conversation`** 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":"conversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversation":{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event chatmessage-deleted **Event topic** : `tutorhub-messaging-service-chatmessage-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 `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":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event chatmessage-updated **Event topic** : `tutorhub-messaging-service-chatmessage-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 `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":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Index Event chatmessage-created **Event topic**: `elastic-index-tutorhub_chatmessage-created` **Event payload**: ```json {"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmessage-updated **Event topic**: `elastic-index-tutorhub_chatmessage-created` **Event payload**: ```json {"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmessage-deleted **Event topic**: `elastic-index-tutorhub_chatmessage-deleted` **Event payload**: ```json {"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmessage-extended **Event topic**: `elastic-index-tutorhub_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 conversation-created **Event topic** : `tutorhub-messaging-service-conversation-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 `conversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`conversation`** 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":"conversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversation":{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event systemmessage-sent **Event topic** : `tutorhub-messaging-service-systemmessage-sent` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `conversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`conversation`** 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":"conversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversation":{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event chatmessage-deleted **Event topic** : `tutorhub-messaging-service-chatmessage-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 `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":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event chatmessage-updated **Event topic** : `tutorhub-messaging-service-chatmessage-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 `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":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Index Event chatmoderation-created **Event topic**: `elastic-index-tutorhub_chatmoderation-created` **Event payload**: ```json {"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmoderation-updated **Event topic**: `elastic-index-tutorhub_chatmoderation-created` **Event payload**: ```json {"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmoderation-deleted **Event topic**: `elastic-index-tutorhub_chatmoderation-deleted` **Event payload**: ```json {"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"} ``` ## Index Event chatmoderation-extended **Event topic**: `elastic-index-tutorhub_chatmoderation-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 conversation-created **Event topic** : `tutorhub-messaging-service-conversation-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 `conversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`conversation`** 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":"conversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversation":{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event systemmessage-sent **Event topic** : `tutorhub-messaging-service-systemmessage-sent` **Event payload**: The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the `conversation` data object itself. The following JSON included in the payload illustrates the fullest representation of the **`conversation`** 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":"conversation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversation":{"id":"ID","conversationType":"String","conversationType_idx":"Integer","participantA":"ID","participantB":"ID","enrollmentId":"ID","lastMessageAt":"Date","lastMessagePreview":"String","status":"String","status_idx":"Integer","participantAName":"String","participantBName":"String","courseTitle":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event chatmessage-deleted **Event topic** : `tutorhub-messaging-service-chatmessage-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 `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":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` ## Route Event chatmessage-updated **Event topic** : `tutorhub-messaging-service-chatmessage-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 `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":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"chatMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chatMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","replyTo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}} ``` # 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 conversation # Service Design Specification - Object Design for conversation **tutorhub-messaging-service** documentation ## Document Overview This document outlines the object design for the `conversation` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## conversation Data Object ### Object Overview **Description:** Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the `ObjectSettings` pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis. ### Core Configuration - **Soft Delete:** Enabled — Determines whether records are marked inactive (`isActive = false`) instead of being physically deleted. - **Public Access:** accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules. ### Composite Indexes - **unique_conversation_pair**: [participantA, participantB, enrollmentId] This composite index is defined to optimize query performance for complex queries involving multiple fields. The index also defines a conflict resolution strategy for duplicate key violations. When a new record would violate this composite index, the following action will be taken: **On Duplicate**: `throwError` An error will be thrown, preventing the insertion of conflicting data. ### Properties Schema | Property | Type | Required | Description | |----------|------|----------|-------------| | `conversationType` | String | Yes | Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. | | `participantA` | ID | Yes | First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. | | `participantB` | ID | Yes | Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. | | `enrollmentId` | ID | No | FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. | | `lastMessageAt` | Date | No | Timestamp of the most recent message. Used for sorting conversations in inbox. | | `lastMessagePreview` | String | No | Truncated preview of last message content. Shown in conversation list. | | `status` | String | Yes | Conversation status: active or closed. | | `participantAName` | String | No | Cached display name of participant A for quick rendering in conversation list. | | `participantBName` | String | No | Cached display name of participant B for quick rendering in conversation list. | | `courseTitle` | String | No | Cached course pack title for display. Set on conversation creation for studentTutor type. | * 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. - **conversationType**: 'default' - **participantA**: '00000000-0000-0000-0000-000000000000' - **participantB**: '00000000-0000-0000-0000-000000000000' - **status**: active ### 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 `active` ### Constant Properties `conversationType` `participantA` `participantB` `enrollmentId` 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 `conversationType` `participantA` `participantB` `enrollmentId` `lastMessageAt` `lastMessagePreview` `status` `participantAName` `participantBName` `courseTitle` 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. - **conversationType**: [studentTutor, adminStudent, adminTutor] - **status**: [active, closed] ### Elastic Search Indexing `conversationType` `participantA` `participantB` `enrollmentId` `lastMessageAt` `status` `participantAName` `participantBName` `courseTitle` 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 `conversationType` `participantA` `participantB` `enrollmentId` `lastMessageAt` `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 `participantA` `participantB` `enrollmentId` 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. - **participantA**: 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 - **participantB**: 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 - **enrollmentId**: ID Relation to `enrollment`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. On Delete: Set Null Required: No --- ### Service Design Specification - Object Design for chatMessage # Service Design Specification - Object Design for chatMessage **tutorhub-messaging-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:** Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. 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 | |----------|------|----------|-------------| | `roomId` | ID | Yes | Reference to the room this message belongs to | | `senderId` | ID | No | Reference to the user who sent this message | | `senderName` | String | No | Display name of the sender (denormalized from user profile at send time) | | `senderAvatar` | String | No | Avatar URL of the sender (denormalized from user profile at send time) | | `messageType` | Enum | Yes | Content type discriminator for this message | | `content` | Object | Yes | Type-specific content payload (structure depends on messageType) | | `timestamp` | | No | Message creation time | | `status` | Enum | No | Message moderation status | | `replyTo` | Object | No | Reply thread reference { id, preview } | * 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. - **roomId**: '00000000-0000-0000-0000-000000000000' - **messageType**: "text" - **content**: {} - **timestamp**: now() - **status**: approved ### Constant Properties `roomId` `senderId` `senderName` `senderAvatar` `messageType` `timestamp` `replyTo` 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 `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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. - **messageType**: [text, image, document, system, warning] - **status**: [pending, approved, rejected] ### Elastic Search Indexing `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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 `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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 `roomId` 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 `senderId` 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. - **senderId**: ID property will be mapped to the session parameter `userId`. ### Filter Properties `roomId` `senderId` `senderName` `senderAvatar` `messageType` `content` `timestamp` `status` `replyTo` 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. - **roomId**: ID has a filter named `roomId` - **senderId**: ID has a filter named `senderId` - **senderName**: String has a filter named `senderName` - **senderAvatar**: String has a filter named `senderAvatar` - **messageType**: Enum has a filter named `messageType` - **content**: Object has a filter named `content` - **timestamp**: has a filter named `timestamp` - **status**: Enum has a filter named `status` - **replyTo**: Object has a filter named `replyTo` --- ### Service Design Specification - Object Design for chatModeration # Service Design Specification - Object Design for chatModeration **tutorhub-messaging-service** documentation ## Document Overview This document outlines the object design for the `chatModeration` model in our application. It includes details about the model's attributes, relationships, and any specific validation or business logic that applies. ## chatModeration Data Object ### Object Overview **Description:** Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. 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 | |----------|------|----------|-------------| | `roomId` | ID | Yes | Reference to the room where the moderation action applies | | `userId` | ID | Yes | The user who is blocked or silenced | | `action` | Enum | Yes | Moderation action type | | `reason` | Text | No | Optional reason for the moderation action | | `duration` | Integer | No | Duration in seconds. 0 means permanent | | `expiresAt` | | No | Expiry timestamp. Null means permanent | | `issuedBy` | ID | No | The moderator who issued the action | * 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. - **roomId**: '00000000-0000-0000-0000-000000000000' - **userId**: '00000000-0000-0000-0000-000000000000' - **action**: "blocked" - **duration**: 0 ### Constant Properties `roomId` `userId` `action` `duration` `expiresAt` `issuedBy` 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 `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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**: [blocked, silenced] ### Elastic Search Indexing `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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 `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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 `roomId` `userId` 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 `roomId` 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. - **roomId**: ID Relation to `conversation`.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 `issuedBy` 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. - **issuedBy**: ID property will be mapped to the session parameter `userId`. ### Filter Properties `roomId` `userId` `action` `reason` `duration` `expiresAt` `issuedBy` 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. - **roomId**: ID has a filter named `roomId` - **userId**: ID has a filter named `userId` - **action**: Enum has a filter named `action` - **reason**: Text has a filter named `reason` - **duration**: Integer has a filter named `duration` - **expiresAt**: has a filter named `expiresAt` - **issuedBy**: ID has a filter named `issuedBy` --- ## Business APIs ### Business API Design Specification - `Create Conversation` # Business API Design Specification - `Create Conversation` 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 `createConversation` 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 `createConversation` Business API is designed to handle a `create` operation on the `Conversation` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Creates a new conversation between two participants. For studentTutor type, requires valid enrollment. For adminStudent/adminTutor, only admin can create. ## API Frontend Description By The Backend Architect ## Create Conversation - Tutors/students can create studentTutor conversations. - Only admin can create adminStudent or adminTutor conversations. - Before creating, check if conversation already exists between the two participants of same type. ## 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 `conversation-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 `createConversation` Business API includes a REST controller that can be triggered via the following route: `/v1/conversations` 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 `createConversation` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `createConversation` Business API has 10 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `conversationId` | `ID` | `No` | `-` | `body` | `conversationId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `conversationType` | `String` | `Yes` | `-` | `body` | `conversationType` | | **Description:** | Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. | | | | | | | | | | | | | `participantA` | `ID` | `Yes` | `-` | `body` | `participantA` | | **Description:** | First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. | | | | | | | | | | | | | `participantB` | `ID` | `Yes` | `-` | `body` | `participantB` | | **Description:** | Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. | | | | | | | | | | | | | `enrollmentId` | `ID` | `No` | `-` | `body` | `enrollmentId` | | **Description:** | FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. | | | | | | | | | | | | | `lastMessageAt` | `Date` | `No` | `-` | `body` | `lastMessageAt` | | **Description:** | Timestamp of the most recent message. Used for sorting conversations in inbox. | | | | | | | | | | | | | `lastMessagePreview` | `String` | `No` | `-` | `body` | `lastMessagePreview` | | **Description:** | Truncated preview of last message content. Shown in conversation list. | | | | | | | | | | | | | `participantAName` | `String` | `No` | `-` | `body` | `participantAName` | | **Description:** | Cached display name of participant A for quick rendering in conversation list. | | | | | | | | | | | | | `participantBName` | `String` | `No` | `-` | `body` | `participantBName` | | **Description:** | Cached display name of participant B for quick rendering in conversation list. | | | | | | | | | | | | | `courseTitle` | `String` | `No` | `-` | `body` | `courseTitle` | | **Description:** | Cached course pack title for display. Set on conversation creation for studentTutor type. | | | | | | | | | | | | ### 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 `createConversation` 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.conversationId, conversationType: this.conversationType, participantA: this.participantA, participantB: this.participantB, enrollmentId: this.enrollmentId, lastMessageAt: this.lastMessageAt, lastMessagePreview: this.lastMessagePreview, participantAName: this.participantAName, participantBName: this.participantBName, courseTitle: this.courseTitle, 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 `createConversation` api has got 9 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationType | String | true | request.body?.["conversationType"] | | participantA | ID | true | request.body?.["participantA"] | | participantB | ID | true | request.body?.["participantB"] | | enrollmentId | ID | false | request.body?.["enrollmentId"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | | lastMessagePreview | String | false | request.body?.["lastMessagePreview"] | | participantAName | String | false | request.body?.["participantAName"] | | participantBName | String | false | request.body?.["participantBName"] | | courseTitle | String | false | request.body?.["courseTitle"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/conversations** ```js axios({ method: 'POST', url: '/v1/conversations', data: { conversationType:"String", participantA:"ID", participantB:"ID", enrollmentId:"ID", lastMessageAt:"Date", lastMessagePreview:"String", participantAName:"String", participantBName:"String", courseTitle:"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 **`conversation`** 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": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Get Conversation` # Business API Design Specification - `Get Conversation` 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 `getConversation` 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 `getConversation` Business API is designed to handle a `get` operation on the `Conversation` 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 single conversation by ID. Only participants or admin can view. ## 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 `getConversation` Business API includes a REST controller that can be triggered via the following route: `/v1/conversations/:conversationId` 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 `getConversation` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `getConversation` 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` | `-` | `urlpath` | `conversationId` | | **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 `getConversation` 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.conversationId},{isActive:true}]}), {"path":"services[5].businessLogic[1].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 `getConversation` api has got 1 regular client parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/conversations/:conversationId** ```js axios({ method: 'GET', url: `/v1/conversations/${conversationId}`, 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 **`conversation`** 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": "conversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" } } } ``` --- ### Business API Design Specification - `List Myconversations` # Business API Design Specification - `List Myconversations` 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 `listMyConversations` 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 `listMyConversations` Business API is designed to handle a `list` operation on the `Conversation` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Lists all conversations where the current user is a participant. Sorted by lastMessageAt descending. ## API Frontend Description By The Backend Architect ## Inbox / Conversation List - Shows all conversations for the logged-in user sorted by most recent. - Show: other participant name, last message preview, timestamp, unread badge. - For adminStudent type show 'Admin Notice' label. For adminTutor show 'Admin' label. - Clicking opens the chat view. ## 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 `listMyConversations` Business API includes a REST controller that can be triggered via the following route: `/v1/myconversations` 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 `listMyConversations` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `listMyConversations` 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 `listMyConversations` 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 { $or: [{ participantA: this.session.userId }, { participantB: 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:[{ $or: [{ participantA: this.session.userId }, { participantB: this.session.userId }] },{isActive:true}]}), {"path":"services[5].businessLogic[2].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 `listMyConversations` api has got no visible parameters. ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/myconversations** ```js axios({ method: 'GET', url: '/v1/myconversations', 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 **`conversations`** 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": "conversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "conversations": [ { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` --- ### Business API Design Specification - `Send Systemmessage` # Business API Design Specification - `Send Systemmessage` 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 `sendSystemMessage` 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 `sendSystemMessage` Business API is designed to handle a `create` operation on the `Conversation` data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow. ## API Description Interservice API called by adminPanel for moderation warnings. Creates/finds admin conversation with target user and sends a warning message. M2M only. ## API Frontend Description By The Backend Architect This API is not called from frontend. It is an interservice endpoint for adminPanel to deliver moderation warnings as chat messages. ## 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 `systemmessage-sent` 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 `sendSystemMessage` Business API includes a REST controller that can be triggered via the following route: `/v1/sendsystemmessage` 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 `sendSystemMessage` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `sendSystemMessage` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `conversationId` | `ID` | `No` | `-` | `body` | `conversationId` | | **Description:** | This id paremeter is used to create the data object with a given specific id. Leave null for automatic id. | | | | | | | | | | | | | `targetUserId` | `ID` | `Yes` | `-` | `body` | `targetUserId` | | **Description:** | The userId of the user to send the warning to | | | | | | | | | | | | | `targetUserRole` | `String` | `Yes` | `-` | `body` | `targetUserRole` | | **Description:** | Role of target: student or tutor. Determines conversation type | | | | | | | | | | | | | `messageContent` | `Text` | `Yes` | `-` | `body` | `messageContent` | | **Description:** | The warning message content | | | | | | | | | | | | | `resolutionType` | `String` | `No` | `-` | `body` | `resolutionType` | | **Description:** | Moderation resolution type: warn, requireEdit, removeCourse, suspend, ban | | | | | | | | | | | | | `complaintId` | `ID` | `No` | `-` | `body` | `complaintId` | | **Description:** | Reference to original complaint/issue ID | | | | | | | | | | | | | `severity` | `String` | `No` | `warning` | `body` | `severity` | | **Description:** | Warning severity: info, warning, critical | | | | | | | | | | | | ### 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 `sendSystemMessage` 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** *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.conversationId, conversationType: this.conversationType, participantA: this.participantA, participantB: this.participantB, enrollmentId: this.enrollmentId, lastMessageAt: this.lastMessageAt, lastMessagePreview: this.lastMessagePreview, participantAName: this.participantAName, participantBName: this.participantBName, courseTitle: this.courseTitle, 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 `sendSystemMessage` api has got 6 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | targetUserId | ID | true | request.body?.["targetUserId"] | | targetUserRole | String | true | request.body?.["targetUserRole"] | | messageContent | Text | true | request.body?.["messageContent"] | | resolutionType | String | false | request.body?.["resolutionType"] | | complaintId | ID | false | request.body?.["complaintId"] | | severity | String | false | request.body?.["severity"] | ### REST Request To access the api you can use the **REST** controller with the path **POST /v1/sendsystemmessage** ```js axios({ method: 'POST', url: '/v1/sendsystemmessage', data: { targetUserId:"ID", targetUserRole:"String", messageContent:"Text", resolutionType:"String", complaintId:"ID", severity:"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 **`conversation`** 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": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "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 messages in a chat hub room. Accessible by admins and room participants. ## 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 `listChatMessages` Business API includes a REST controller that can be triggered via the following route: `/v1/v1/chat-messages` 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 9 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 `listChatMessages` api supports 9 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for `list` type APIs. #### `roomId` Filter **Type:** `ID` **Description:** Reference to the room this message belongs to **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?roomId=` - Multiple values: `?roomId=&roomId=` - Null check: `?roomId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/v1/chat-messages?roomId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/v1/chat-messages?roomId=550e8400-e29b-41d4-a716-446655440000&roomId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/v1/chat-messages?roomId=null ``` #### `senderId` Filter **Type:** `ID` **Description:** Reference to the user who sent this message **Location:** Query Parameter **Usage:** **Non-Array Property:** - Single value: `?senderId=` - Multiple values: `?senderId=&senderId=` - Null check: `?senderId=null` **Examples:** ```javascript // Get records with a specific ID GET /v1/v1/chat-messages?senderId=550e8400-e29b-41d4-a716-446655440000 // Get records with multiple IDs (use multiple parameters) GET /v1/v1/chat-messages?senderId=550e8400-e29b-41d4-a716-446655440000&senderId=660e8400-e29b-41d4-a716-446655440001 // Get records without this field GET /v1/v1/chat-messages?senderId=null ``` #### `senderName` Filter **Type:** `String` **Description:** Display name of the sender (denormalized from user profile at send time) **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?senderName=` (matches any string containing the value, case-insensitive) - Multiple values: `?senderName=&senderName=` (matches records containing any of the values) - Null check: `?senderName=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/v1/chat-messages?senderName=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/v1/chat-messages?senderName=laptop&senderName=phone&senderName=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/v1/chat-messages?senderName=null ``` #### `senderAvatar` Filter **Type:** `String` **Description:** Avatar URL of the sender (denormalized from user profile at send time) **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?senderAvatar=` (matches any string containing the value, case-insensitive) - Multiple values: `?senderAvatar=&senderAvatar=` (matches records containing any of the values) - Null check: `?senderAvatar=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/v1/chat-messages?senderAvatar=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/v1/chat-messages?senderAvatar=laptop&senderAvatar=phone&senderAvatar=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/v1/chat-messages?senderAvatar=null ``` #### `messageType` Filter **Type:** `Enum` **Description:** Content type discriminator for this message **Location:** Query Parameter **Usage:** - Single value: `?messageType=` (case-insensitive) - Multiple values: `?messageType=&messageType=` - Null check: `?messageType=null` **Examples:** ```javascript // Get records with specific enum value GET /v1/v1/chat-messages?messageType=active // Get records with multiple enum values (use multiple parameters) GET /v1/v1/chat-messages?messageType=active&messageType=pending // Get records without this field GET /v1/v1/chat-messages?messageType=null ``` #### `content` Filter **Type:** `Object` **Description:** Type-specific content payload (structure depends on messageType) **Location:** Query Parameter **Usage:** - Single value: `?content=` - Multiple values: `?content=&content=` - Null check: `?content=null` **Examples:** ```javascript // Get records with specific value GET /v1/v1/chat-messages?content= // Get records with multiple values (use multiple parameters) GET /v1/v1/chat-messages?content=&content= // Get records without this field GET /v1/v1/chat-messages?content=null ``` #### `timestamp` Filter **Type:** `String` **Description:** Message creation time **Location:** Query Parameter **Usage:** **Non-Array Property (Case-Insensitive Partial Matching):** - Single value: `?timestamp=` (matches any string containing the value, case-insensitive) - Multiple values: `?timestamp=×tamp=` (matches records containing any of the values) - Null check: `?timestamp=null` **Examples:** ```javascript // Find records with "john" in the field (case-insensitive partial match) GET /v1/v1/chat-messages?timestamp=john // Matches: "John", "Johnny", "johnson", "McJohn", etc. // Find records with multiple values (use multiple parameters) GET /v1/v1/chat-messages?timestamp=laptop×tamp=phone×tamp=tablet // Matches records containing "laptop", "phone", or "tablet" anywhere in the field // Find records without this field GET /v1/v1/chat-messages?timestamp=null ``` #### `status` Filter **Type:** `Enum` **Description:** Message moderation 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/v1/chat-messages?status=active // Get records with multiple enum values (use multiple parameters) GET /v1/v1/chat-messages?status=active&status=pending // Get records without this field GET /v1/v1/chat-messages?status=null ``` #### `replyTo` Filter **Type:** `Object` **Description:** Reply thread reference { id, preview } **Location:** Query Parameter **Usage:** - Single value: `?replyTo=` - Multiple values: `?replyTo=&replyTo=` - Null check: `?replyTo=null` **Examples:** ```javascript // Get records with specific value GET /v1/v1/chat-messages?replyTo= // Get records with multiple values (use multiple parameters) GET /v1/v1/chat-messages?replyTo=&replyTo= // Get records without this field GET /v1/v1/chat-messages?replyTo=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 `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: `[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[5].businessLogic[4].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). [ timestamp 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 `listChatMessages` api has 9 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 | | ---------------------- | ---------------------- | -------------- | ----------------------------- | | roomId | ID | No | Reference to the room this message belongs to | | senderId | ID | No | Reference to the user who sent this message | | senderName | String | No | Display name of the sender (denormalized from user profile at send time) | | senderAvatar | String | No | Avatar URL of the sender (denormalized from user profile at send time) | | messageType | Enum | No | Content type discriminator for this message | | content | Object | No | Type-specific content payload (structure depends on messageType) | | timestamp | String | No | Message creation time | | status | Enum | No | Message moderation status | | replyTo | Object | No | Reply thread reference { id, preview } | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages** ```js axios({ method: 'GET', url: '/v1/v1/chat-messages', data: { }, params: { // Filter parameters (see Filter Parameters section for usage examples) // roomId: '' // Filter by roomId // senderId: '' // Filter by senderId // senderName: '' // Filter by senderName // senderAvatar: '' // Filter by senderAvatar // messageType: '' // Filter by messageType // content: '' // Filter by content // timestamp: '' // Filter by timestamp // status: '' // Filter by status // replyTo: '' // Filter by replyTo } }); ``` ### 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", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "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 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 single chat hub message 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 `getChatMessage` Business API includes a REST controller that can be triggered via the following route: `/v1/v1/chat-messages/:id` 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 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `chatMessageId` | `ID` | `Yes` | `-` | `urlpath` | `chatMessageId` | | **Description:** | This id paremeter is used to query the required data object. | | | | | | | | | | | | | `id` | `String` | `Yes` | `-` | `urlpath` | `id` | | **Description:** | This parameter will be used to select the data object that is queried | | | | | | | | | | | | ### 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: `[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.chatMessageId},{isActive:true}]}), {"path":"services[5].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 `getChatMessage` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | ### REST Request To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages/:id** ```js axios({ method: 'GET', url: `/v1/v1/chat-messages/${id}`, 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", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Delete Chatmessage` # Business API Design Specification - `Delete 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 `deleteChatMessage` 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 `deleteChatMessage` Business API is designed to handle a `delete` 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 Delete a chat hub message. Admins can delete any message; users can delete their own. ## 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 `chatmessage-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 `deleteChatMessage` Business API includes a REST controller that can be triggered via the following route: `/v1/v1/chat-messages/:id` 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 `deleteChatMessage` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `deleteChatMessage` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `chatMessageId` | `ID` | `Yes` | `-` | `urlpath` | `chatMessageId` | | **Description:** | This id paremeter is used to select the required data object that will be deleted | | | | | | | | | | | | | `id` | `String` | `Yes` | `-` | `urlpath` | `id` | | **Description:** | This parameter will be used to select the data object that want to 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 `deleteChatMessage` 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]` --- ## 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[5].businessLogic[6].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 `deleteChatMessage` api has got 2 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | ### REST Request To access the api you can use the **REST** controller with the path **DELETE /v1/v1/chat-messages/:id** ```js axios({ method: 'DELETE', url: `/v1/v1/chat-messages/${id}`, 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": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ### Business API Design Specification - `Update Chatmessage` # Business API Design Specification - `Update 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 `updateChatMessage` 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 `updateChatMessage` Business API is designed to handle a `update` 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 Update a chat hub message content. Only the message sender or admins can edit. ## 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 `chatmessage-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 `updateChatMessage` Business API includes a REST controller that can be triggered via the following route: `/v1/v1/chat-messages/:id` 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 `updateChatMessage` Business API will be registered as a tool on the MCP server within the service binding. ## API Parameters The `updateChatMessage` 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 | | ----------------------------------------------- | --------------------- | -------------------------------------- | -------------------------------------------------------------------- | --------------------------- | ------------------------------ | | | | | | | | | `chatMessageId` | `ID` | `Yes` | `-` | `urlpath` | `chatMessageId` | | **Description:** | This id paremeter is used to select the required data object that will be updated | | | | | | | | | | | | | `content` | `Object` | `No` | `-` | `body` | `content` | | **Description:** | Type-specific content payload (structure depends on messageType) | | | | | | | | | | | | | `status` | `Enum` | `No` | `-` | `body` | `status` | | **Description:** | Message moderation status | | | | | | | | | | | | | `id` | `String` | `Yes` | `-` | `urlpath` | `id` | | **Description:** | This parameter will be used to select the data object that want 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 `updateChatMessage` 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]` --- ## 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[5].businessLogic[7].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 { content: this.content ? (typeof this.content == 'string' ? JSON.parse(this.content) : this.content) : null, status: this.status, } ``` ## 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 `updateChatMessage` api has got 4 regular client parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | content | Object | false | request.body?.["content"] | | status | Enum | false | request.body?.["status"] | | id | String | true | request.params?.["id"] | ### REST Request To access the api you can use the **REST** controller with the path **PATCH /v1/v1/chat-messages/:id** ```js axios({ method: 'PATCH', url: `/v1/v1/chat-messages/${id}`, data: { content:"Object", 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 **`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": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- ## Realtime Hubs ### Realtime Hub Design Specification - `chat` # Realtime Hub Design Specification - `chat` This document provides a detailed architectural overview of the `chat` realtime hub within the `messaging` service. It covers the hub's room management, message handling, role-based authorization, event system, and server-side logic. ## Hub Overview **Description:** Real-time chat hub for TutorHub. Supports three channel types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings to students), adminTutor (bidirectional admin-tutor communication). Authorization is role-aware: students in adminStudent rooms get viewer role (read-only). - **Socket.IO Namespace:** `/hub/chat` - **Room DataObject:** `conversation` ## Room Settings Rooms are backed by the `conversation` DataObject. Each record in this object represents a room that users can join. ### Room Eligibility Before authorization checks, the following condition is evaluated. If it returns false, nobody can join the room: ```js conversation.status == 'active' ``` ### Authorization Flow The hub uses a layered authorization flow to determine each user's role when joining a room: 1. **Absolute Roles:** Users with roles `superAdmin` bypass all checks and receive the `system` hub role with full permissions. 4. **Auth Sources:** The following DataObject-based authorization sources are checked in order. The first match determines the user's hub role: 1. **participantACheck** 2. **participantBAdminStudent** 3. **participantBCheck** ## Hub Roles | Role | Read | Send | Moderate | Delete Any | Manage Room | Moderated | |------|------|------|----------|------------|-------------|-----------| | `member` | Yes | Yes | No | No | No | No | | `viewer` | Yes | No | No | No | No | No | ## Message Settings - **Message DataObject:** `chatMessage` ### Built-in Message Types The following message types are supported: - `text` - `image` - `document` - `system` ### Cross-Cutting Features - **Reply Threading:** Enabled — messages can reference a parent message via `replyTo` - **Reactions:** Disabled - **Forwarded Flag:** Disabled ### Custom Message Types - **warning**: Admin warning message sent as part of moderation actions. Rendered with amber/yellow alert styling in the frontend. Fields: `[{"name":"body","fieldType":"Text","required":true,"description":"The warning message content"},{"name":"resolutionType","fieldType":"String","required":false,"description":"The moderation resolution type: warn, requireEdit, removeCourse, suspend, ban"},{"name":"complaintId","fieldType":"ID","required":false,"description":"Reference to the original complaint/issue ID"},{"name":"severity","fieldType":"Enum","required":true,"description":"Warning severity level","enumValues":"info,warning,critical","defaultValue":"warning"}]` ## Event Settings ### Standard Events | Event | Enabled | Type | |-------|---------|------| | Typing Indicator | Yes | Ephemeral | | Recording Indicator | No | Ephemeral | | Read Receipts | Yes | Persisted | | Delivery Receipts | No | Persisted | | Presence | Yes | Ephemeral | ### Auto-Bridged DataObject Events Auto-bridging of DataObject CRUD events is disabled for this hub. ## History Settings ## Guardrails | Setting | Value | |---------|-------| | Max Users Per Room | 10 | | Max Rooms Per User | 100 | | Message Rate Limit | 30 msg/min | | Max Message Size | 65536 bytes | | Connection Timeout | 300000 ms | | Auth Cache TTL | 300 seconds | | Global Moderation | No | | Default Silenced | No | ## Server-Side Logic --- *This document was generated from the realtime hub configuration and should be kept in sync with design changes.* --- # AgentHub Service ## Service Design Specification # Service Design Specification **tutorhub-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 `tutorhub-agenthub-service`. This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/agenthub-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/agenthub-api` * **Production:** `https://tutorhub.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 `tutorhub-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 ## tutorhub-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 | tutorhub-access-token| | Cookie | tutorhub-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://tutorhub.prw.mindbricks.com/agenthub-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/agenthub-api` * **Production:** `https://tutorhub.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 ## tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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**: `tutorhub-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-tutorhub_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-tutorhub_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-tutorhub_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-tutorhub_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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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-tutorhub_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-tutorhub_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-tutorhub_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-tutorhub_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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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-tutorhub_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-tutorhub_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-tutorhub_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-tutorhub_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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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** : `tutorhub-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 **tutorhub-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 **tutorhub-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 **tutorhub-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[6].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[6].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[6].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[6].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[6].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.21` --- ## 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.21` 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_ `/studentEnrollmentDashboardView` **Example**: ```js axios({ method: "GET", url: `/studentEnrollmentDashboardView`, 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_ `/studentEnrollmentDashboardView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/studentEnrollmentDashboardView/${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_ `/tutorDashboardCoursesView` **Example**: ```js axios({ method: "GET", url: `/tutorDashboardCoursesView`, 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_ `/tutorDashboardCoursesView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/tutorDashboardCoursesView/${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_ `/enrollmentNotificationView` **Example**: ```js axios({ method: "GET", url: `/enrollmentNotificationView`, 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_ `/enrollmentNotificationView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/enrollmentNotificationView/${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_ `/refundNotificationView` **Example**: ```js axios({ method: "GET", url: `/refundNotificationView`, 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_ `/refundNotificationView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/refundNotificationView/${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_ `/preliminaryScreeningDecisionView` **Example**: ```js axios({ method: "GET", url: `/preliminaryScreeningDecisionView`, 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_ `/preliminaryScreeningDecisionView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/preliminaryScreeningDecisionView/${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_ `/enrollmentRequiresScreeningView` **Example**: ```js axios({ method: "GET", url: `/enrollmentRequiresScreeningView`, 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_ `/enrollmentRequiresScreeningView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/enrollmentRequiresScreeningView/${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_ `/deneme` **Example**: ```js axios({ method: "GET", url: `/deneme`, 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_ `/deneme/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/deneme/${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_ `/publicTutorProfileView/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: `/publicTutorProfileView/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_ `/publicTutorProfileView/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: `/publicTutorProfileView/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_ `/publicTutorProfileView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicTutorProfileView/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_ `/publicTutorProfileView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicTutorProfileView/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_ `/publicTutorProfileView/schema` ```js axios({ method: "GET", url: `/publicTutorProfileView/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 /publicTutorProfileView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/publicTutorProfileView/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 /publicTutorProfileView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicTutorProfileView/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 /publicTutorProfileView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/publicTutorProfileView/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_ `/publicTutorProfileView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/publicTutorProfileView/${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_ `/publicCoursePackView/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: `/publicCoursePackView/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_ `/publicCoursePackView/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: `/publicCoursePackView/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_ `/publicCoursePackView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCoursePackView/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_ `/publicCoursePackView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicCoursePackView/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_ `/publicCoursePackView/schema` ```js axios({ method: "GET", url: `/publicCoursePackView/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 /publicCoursePackView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/publicCoursePackView/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 /publicCoursePackView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCoursePackView/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 /publicCoursePackView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/publicCoursePackView/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_ `/publicCoursePackView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/publicCoursePackView/${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_ `/issueReportStatusChangedView/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: `/issueReportStatusChangedView/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_ `/issueReportStatusChangedView/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: `/issueReportStatusChangedView/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_ `/issueReportStatusChangedView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/issueReportStatusChangedView/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_ `/issueReportStatusChangedView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/issueReportStatusChangedView/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_ `/issueReportStatusChangedView/schema` ```js axios({ method: "GET", url: `/issueReportStatusChangedView/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 /issueReportStatusChangedView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/issueReportStatusChangedView/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 /issueReportStatusChangedView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/issueReportStatusChangedView/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 /issueReportStatusChangedView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/issueReportStatusChangedView/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_ `/issueReportStatusChangedView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/issueReportStatusChangedView/${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_ `/contentModerationActionView/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: `/contentModerationActionView/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_ `/contentModerationActionView/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: `/contentModerationActionView/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_ `/contentModerationActionView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/contentModerationActionView/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_ `/contentModerationActionView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/contentModerationActionView/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_ `/contentModerationActionView/schema` ```js axios({ method: "GET", url: `/contentModerationActionView/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 /contentModerationActionView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/contentModerationActionView/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 /contentModerationActionView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/contentModerationActionView/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 /contentModerationActionView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/contentModerationActionView/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_ `/contentModerationActionView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/contentModerationActionView/${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_ `/adminDashboardStatsView/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: `/adminDashboardStatsView/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_ `/adminDashboardStatsView/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: `/adminDashboardStatsView/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_ `/adminDashboardStatsView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/adminDashboardStatsView/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_ `/adminDashboardStatsView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/adminDashboardStatsView/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_ `/adminDashboardStatsView/schema` ```js axios({ method: "GET", url: `/adminDashboardStatsView/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 /adminDashboardStatsView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/adminDashboardStatsView/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 /adminDashboardStatsView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/adminDashboardStatsView/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 /adminDashboardStatsView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/adminDashboardStatsView/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_ `/adminDashboardStatsView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/adminDashboardStatsView/${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_ `/publicCourseCategoryView/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: `/publicCourseCategoryView/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_ `/publicCourseCategoryView/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: `/publicCourseCategoryView/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_ `/publicCourseCategoryView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCourseCategoryView/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_ `/publicCourseCategoryView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicCourseCategoryView/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_ `/publicCourseCategoryView/schema` ```js axios({ method: "GET", url: `/publicCourseCategoryView/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 /publicCourseCategoryView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/publicCourseCategoryView/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 /publicCourseCategoryView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCourseCategoryView/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 /publicCourseCategoryView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/publicCourseCategoryView/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_ `/publicCourseCategoryView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/publicCourseCategoryView/${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: tutorprofile-created **Event Topic**: `elastic-index-tutorhub_tutorprofile-created` When a `tutorprofile` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicTutorProfileViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-updated **Event Topic**: `elastic-index-tutorhub_tutorprofile-updated` When a `tutorprofile` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicTutorProfileViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-deleted **Event Topic**: `elastic-index-tutorhub>_tutorprofile-deleted` When a `tutorprofile` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicTutorProfileViewAggregateData` 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 `tutorUserInfoRePublicTutorProfileView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-tutorhub>_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 `tutorUserInfoRePublicTutorProfileView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-tutorhub>_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 `tutorUserInfoRePublicTutorProfileView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-created **Event Topic**: `elastic-index-coursepack-created` When a `coursepack` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `coursePacksRePublicTutorProfileView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-updated **Event Topic**: `elastic-index-tutorhub>_coursepack-updated` When a `coursepack` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `coursePacksRePublicTutorProfileView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-deleted **Event Topic**: `elastic-index-tutorhub>_coursepack-deleted` When a `coursepack` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `coursePacksRePublicTutorProfileView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-created **Event Topic**: `elastic-index-tutorhub_coursepack-created` When a `coursepack` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicCoursePackViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-updated **Event Topic**: `elastic-index-tutorhub_coursepack-updated` When a `coursepack` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicCoursePackViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-deleted **Event Topic**: `elastic-index-tutorhub>_coursepack-deleted` When a `coursepack` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicCoursePackViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-created **Event Topic**: `elastic-index-tutorprofile-created` When a `tutorprofile` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `tutorProfileRePublicCoursePackView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-updated **Event Topic**: `elastic-index-tutorhub>_tutorprofile-updated` When a `tutorprofile` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `tutorProfileRePublicCoursePackView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-deleted **Event Topic**: `elastic-index-tutorhub>_tutorprofile-deleted` When a `tutorprofile` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `tutorProfileRePublicCoursePackView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursecategory-created **Event Topic**: `elastic-index-coursecategory-created` When a `coursecategory` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `categoryInfoRePublicCoursePackView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursecategory-updated **Event Topic**: `elastic-index-tutorhub>_coursecategory-updated` When a `coursecategory` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `categoryInfoRePublicCoursePackView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursecategory-deleted **Event Topic**: `elastic-index-tutorhub>_coursecategory-deleted` When a `coursecategory` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `categoryInfoRePublicCoursePackView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: adminissue-created **Event Topic**: `elastic-index-tutorhub_adminissue-created` When a `adminissue` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `issueReportStatusChangedViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: adminissue-updated **Event Topic**: `elastic-index-tutorhub_adminissue-updated` When a `adminissue` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `issueReportStatusChangedViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: adminissue-deleted **Event Topic**: `elastic-index-tutorhub>_adminissue-deleted` When a `adminissue` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `issueReportStatusChangedViewAggregateData` 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 `reporterUserReIssueReportStatusChangedView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-tutorhub>_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 `reporterUserReIssueReportStatusChangedView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-tutorhub>_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 `reporterUserReIssueReportStatusChangedView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-created **Event Topic**: `elastic-index-coursepack-created` When a `coursepack` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `relatedCoursePackReIssueReportStatusChangedView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-updated **Event Topic**: `elastic-index-tutorhub>_coursepack-updated` When a `coursepack` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `relatedCoursePackReIssueReportStatusChangedView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-deleted **Event Topic**: `elastic-index-tutorhub>_coursepack-deleted` When a `coursepack` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `relatedCoursePackReIssueReportStatusChangedView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: adminmoderationaction-created **Event Topic**: `elastic-index-tutorhub_adminmoderationaction-created` When a `adminmoderationaction` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `contentModerationActionViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: adminmoderationaction-updated **Event Topic**: `elastic-index-tutorhub_adminmoderationaction-updated` When a `adminmoderationaction` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `contentModerationActionViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: adminmoderationaction-deleted **Event Topic**: `elastic-index-tutorhub>_adminmoderationaction-deleted` When a `adminmoderationaction` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `contentModerationActionViewAggregateData` 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 `adminUserReContentModerationActionView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-updated **Event Topic**: `elastic-index-tutorhub>_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 `adminUserReContentModerationActionView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: user-deleted **Event Topic**: `elastic-index-tutorhub>_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 `adminUserReContentModerationActionView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-created **Event Topic**: `elastic-index-coursepack-created` When a `coursepack` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `targetCoursePackReContentModerationActionView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-updated **Event Topic**: `elastic-index-tutorhub>_coursepack-updated` When a `coursepack` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `targetCoursePackReContentModerationActionView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursepack-deleted **Event Topic**: `elastic-index-tutorhub>_coursepack-deleted` When a `coursepack` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `targetCoursePackReContentModerationActionView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-created **Event Topic**: `elastic-index-tutorprofile-created` When a `tutorprofile` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `targetTutorProfileReContentModerationActionView` function to update dependent documents in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-updated **Event Topic**: `elastic-index-tutorhub>_tutorprofile-updated` When a `tutorprofile` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `targetTutorProfileReContentModerationActionView` function to re-enrich dependent data in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: tutorprofile-deleted **Event Topic**: `elastic-index-tutorhub>_tutorprofile-deleted` When a `tutorprofile` is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `targetTutorProfileReContentModerationActionView` function to handle dependent data cleanup or updates. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: enrollment-created **Event Topic**: `elastic-index-tutorhub_enrollment-created` When a `enrollment` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `adminDashboardStatsViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: enrollment-updated **Event Topic**: `elastic-index-tutorhub_enrollment-updated` When a `enrollment` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `adminDashboardStatsViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: enrollment-deleted **Event Topic**: `elastic-index-tutorhub>_enrollment-deleted` When a `enrollment` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `adminDashboardStatsViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursecategory-created **Event Topic**: `elastic-index-tutorhub_coursecategory-created` When a `coursecategory` is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicCourseCategoryViewAggregateData` function to enrich and store the final document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursecategory-updated **Event Topic**: `elastic-index-tutorhub_coursecategory-updated` When a `coursecategory` is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicCourseCategoryViewAggregateData` function to update the enriched document in the related index. **Expected Payload**: ```json { "id": "String" } ``` ### Kafka Event Listener: coursecategory-deleted **Event Topic**: `elastic-index-tutorhub>_coursecategory-deleted` When a `coursecategory` is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the `publicCourseCategoryViewAggregateData` function to handle removal or cleanup in the related index. **Expected Payload**: ```json { "id": "String" } ``` --- # Notification Service ## Service Design Specification # Service Design Specification **Notification Service Documentation** **Version:** `1.0.111` --- ## 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.111` 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**: `tutorhub-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 `tutorhub-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**: `tutorhub-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 `tutorhub-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**: tutorhub-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 `tutorhub-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**: `tutorhub-notification-service-notification-email` When a notification is sent through the Email channel, this listener is triggered. It consumes messages from the `tutorhub-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**: `tutorhub-notification-service-notification-push` When a notification is sent through the Push channel, this listener is triggered. It consumes messages from the `tutorhub-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**: `tutorhub-notification-service-notification-sms` When a notification is sent through the SMS channel, this listener is triggered. It consumes messages from the `tutorhub-notification-service-notification-sms` topic, parses the payload, and uses the dynamically configured SMS provider to send the notification. ### Kafka Event Listener: runuserEmailVerificationListener **Event Topic**: `tutorhub-auth-service-dbevent-user-created` When a notification is sent through the `tutorhub-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: runenrollmentConfirmedStudentListener **Event Topic**: `tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed` When a notification is sent through the `tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed` 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: runenrollmentConfirmedTutorListener **Event Topic**: `tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed` When a notification is sent through the `tutorhub-enrollmentmanagement-service-enrollment-payment-confirmed` 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: runrefundProcessedStudentListener **Event Topic**: `tutorhub-enrollmentmanagement-service-refund-processed` When a notification is sent through the `tutorhub-enrollmentmanagement-service-refund-processed` 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: runrefundProcessedTutorListener **Event Topic**: `tutorhub-enrollmentmanagement-service-refund-processed` When a notification is sent through the `tutorhub-enrollmentmanagement-service-refund-processed` 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: runpreliminaryScreeningDecisionListener **Event Topic**: `tutorhub-coursescheduling-service-preliminarymeeting-updated` When a notification is sent through the `tutorhub-coursescheduling-service-preliminarymeeting-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 (``). 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: runenrollmentRequiresScreeningListener **Event Topic**: `tutorhub-coursescheduling-service-preliminarymeeting-created` When a notification is sent through the `tutorhub-coursescheduling-service-preliminarymeeting-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: runissueReportStatusChangedListener **Event Topic**: `tutorhub-platformadmin-service-adminissue-updated` When a notification is sent through the `tutorhub-platformadmin-service-adminissue-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 (``). 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: runcontentModerationActionListener **Event Topic**: `tutorhub-platformadmin-service-adminmoderationaction-created` When a notification is sent through the `tutorhub-platformadmin-service-adminmoderationaction-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: runrefundRequestedTutorListener **Event Topic**: `tutorhub-enrollmentmanagement-service-refund-requested` When a notification is sent through the `tutorhub-enrollmentmanagement-service-refund-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: runtutorApplicationApprovedEmailListener **Event Topic**: `tutorhub-auth-service-tutorapplication-reviewed` When a notification is sent through the `tutorhub-auth-service-tutorapplication-reviewed` 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: runcourseRemovedByAdminListener **Event Topic**: `tutorhub-tutorcatalog-service-coursepack-removed-by-admin` When a notification is sent through the `tutorhub-tutorcatalog-service-coursepack-removed-by-admin` 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: runemailVerificationListener **Event Topic**: `tutorhub-user-service-email-verification-start` When a notification is sent through the `tutorhub-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**: `tutorhub-user-service-mobile-verification-start` When a notification is sent through the `tutorhub-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**: `tutorhub-user-service-password-reset-by-email-start` When a notification is sent through the `tutorhub-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**: `tutorhub-user-service-password-reset-by-mobile-start` When a notification is sent through the `tutorhub-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**: `tutorhub-user-service-email-2FA-start` When a notification is sent through the `tutorhub-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**: `tutorhub-user-service-mobile-2FA-start` When a notification is sent through the `tutorhub-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*