# TutorHub Educational Platform - Frontend Development Prompts > AI-assisted frontend development prompts for TutorHub Educational Platform This document contains all frontend development prompts that can be used to build the user interface for this project. Each prompt provides detailed specifications for implementing specific frontend features. --- ## Table of Contents - [Introduction](#introduction) - [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) --- ## Introduction ### Project Overview # 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. --- ### How to Use These Prompts These prompts are designed to be used with AI coding assistants to help build frontend features. Each prompt includes: 1. **Feature Description** - What the feature does and its purpose 2. **Data Models** - The backend data structures to work with 3. **API Endpoints** - Available REST APIs for the feature 4. **UI Requirements** - Specific user interface requirements 5. **Implementation Guidelines** - Best practices and patterns to follow When using these prompts with an AI assistant: - Copy the relevant prompt section - Provide context about your frontend framework (React, Vue, Angular, etc.) - Reference the REST API documentation for endpoint details --- ## Frontend Development Prompts # **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. --- # **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.** --- # **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.** --- # **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.** --- # **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.** --- # **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.** --- # **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.** --- # **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.** --- # **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.** --- # **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. --- # **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.** --- # **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.** --- # **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.** --- # **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.** --- --- ## Related Documentation For more detailed information, refer to: - **[llms.txt](/document/llms.txt)** - Documentation overview and index - **[llms-restapi.txt](/document/llms-restapi.txt)** - Complete REST API reference - **[llms-full.txt](/document/llms-full.txt)** - Complete documentation --- *Generated by Mindbricks Genesis Engine*