# TutorHub Educational Platform - REST API Reference > Complete REST API documentation for all services in TutorHub Educational Platform This document provides comprehensive REST API documentation for all services. Use this reference to understand available endpoints, request/response formats, and authentication requirements. --- ## Table of Contents - [Introduction](#introduction) - [Auth Service REST API](#auth-service-rest-api-guide) - [TutorCatalog Service REST API](#tutorcatalog-service-rest-api-guide) - [CourseScheduling Service REST API](#coursescheduling-service-rest-api-guide) - [EnrollmentManagement Service REST API](#enrollmentmanagement-service-rest-api-guide) - [PlatformAdmin Service REST API](#platformadmin-service-rest-api-guide) - [Messaging Service REST API](#messaging-service-rest-api-guide) - [AgentHub Service REST API](#agenthub-service-rest-api-guide) - [Bff Service REST API](#bff-service-rest-api-guide) - [Notification Service REST API](#notification-service-rest-api-guide) --- ## Introduction # 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. --- ## Service API Documentation # REST API GUIDE ## tutorhub-auth-service **Version:** `1.0.52` Authentication service for the project ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Auth Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Auth Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Auth Service via HTTP requests for purposes such as creating, updating, deleting and querying Auth objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the Auth Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the Auth service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the Auth service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Auth service. This service is configured to listen for HTTP requests on port `3011`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/auth-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/auth-api` * **Production:** `https://tutorhub.mindbricks.co/auth-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the Auth service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `Auth` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Auth` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `Auth` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources Auth service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### User resource *Resource Definition* : A data object that stores the user information and handles login settings. *User Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **email** | String | | | * A string value to represent the user's email.* | | **password** | String | | | * A string value to represent the user's password. It will be stored as hashed.* | | **fullname** | String | | | *A string value to represent the fullname of the user* | | **avatar** | String | | | *The avatar url of the user. A random avatar will be generated if not provided* | | **roleId** | String | | | *A string value to represent the roleId of the user.* | | **emailVerified** | Boolean | | | *A boolean value to represent the email verification status of the user.* | | **tutorApplicationStatus** | String | | | ** | | **certifications** | Text | | | *Tutor applicant's professional certifications.* | | **qualifications** | Text | | | *Tutor applicant's educational qualifications.* | | **bio** | Text | | | *Short professional bio for the tutor applicant.* | | **specializations** | String | | | *Subject areas the tutor specializes in.* | | **applicationReviewNote** | Text | | | ** | | **applicationDocuments** | String | | | *URLs of uploaded documents for tutor application.* | | **accountStatus** | String | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### tutorApplicationStatus Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **none** | `"none""` | 0 | | **pending** | `"pending""` | 1 | | **approved** | `"approved""` | 2 | | **rejected** | `"rejected""` | 3 | ##### accountStatus Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **suspended** | `"suspended""` | 1 | | **banned** | `"banned""` | 2 | ### UserAvatarsFile resource *Resource Definition* : Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. *UserAvatarsFile Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **fileName** | String | | | *Original file name as uploaded by the client.* | | **mimeType** | String | | | *MIME type of the uploaded file (e.g., image/png, application/pdf).* | | **fileSize** | Integer | | | *File size in bytes.* | | **accessKey** | String | | | *12-character random key for shareable access. Auto-generated on upload.* | | **ownerId** | ID | | | *ID of the user who uploaded the file (from session).* | | **fileData** | Blob | | | *Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.* | | **metadata** | Object | | | *Optional JSON metadata for the file (tags, alt text, etc.).* | | **userId** | ID | | | *Reference to the owner user record.* | ## Business Api ### `Get User` API This api is used by admin roles or the users themselves to get the user profile information. **Rest Route** The `getUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `getUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users/:userId** ```js axios({ method: 'GET', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update User` API This route is used by admins to update user profiles. **Rest Route** The `updateUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `updateUser` api has got 11 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/users/:userId** ```js axios({ method: 'PATCH', url: `/v1/users/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Profile` API This route is used by users to update their profiles. **Rest Route** The `updateProfile` API REST controller can be triggered via the following route: `/v1/profile/:userId` **Rest Request Parameters** The `updateProfile` api has got 11 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/profile/:userId** ```js axios({ method: 'PATCH', url: `/v1/profile/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create User` API This api is used by admin roles to create a new user manually from admin panels **Rest Route** The `createUser` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** The `createUser` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | email | String | true | request.body?.["email"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **email** : A string value to represent the user's email. **password** : A string value to represent the user's password. It will be stored as hashed. **fullname** : A string value to represent the fullname of the user **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/users** ```js axios({ method: 'POST', url: '/v1/users', data: { avatar:"String", email:"String", password:"String", fullname:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete User` API This api is used by admins to delete user profiles. **Rest Route** The `deleteUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `deleteUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/users/:userId** ```js axios({ method: 'DELETE', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Archive Profile` API This api is used by users to archive their profiles. **Rest Route** The `archiveProfile` API REST controller can be triggered via the following route: `/v1/archiveprofile/:userId` **Rest Request Parameters** The `archiveProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/archiveprofile/:userId** ```js axios({ method: 'DELETE', url: `/v1/archiveprofile/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Users` API The list of users is filtered by the tenantId. **Rest Route** The `listUsers` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** **Filter Parameters** The `listUsers` api supports 3 optional filter parameters for filtering list results: **email** (`String`): A string value to represent the user's email. - Single (partial match, case-insensitive): `?email=` - Multiple: `?email=&email=` - Null: `?email=null` **fullname** (`String`): A string value to represent the fullname of the user - Single (partial match, case-insensitive): `?fullname=` - Multiple: `?fullname=&fullname=` - Null: `?fullname=null` **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users** ```js axios({ method: 'GET', url: '/v1/users', data: { }, params: { // Filter parameters (see Filter Parameters section above) // email: '' // Filter by email // fullname: '' // Filter by fullname // roleId: '' // Filter by roleId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Search Users` API The list of users is filtered by the tenantId. **Rest Route** The `searchUsers` API REST controller can be triggered via the following route: `/v1/searchusers` **Rest Request Parameters** The `searchUsers` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | keyword | String | true | request.query?.["keyword"] | **keyword** : **Filter Parameters** The `searchUsers` api supports 1 optional filter parameter for filtering list results: **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/searchusers** ```js axios({ method: 'GET', url: '/v1/searchusers', data: { }, params: { keyword:'"String"', // Filter parameters (see Filter Parameters section above) // roleId: '' // Filter by roleId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Userrole` API This route is used by admin roles to update the user role.The default role is user when a user is registered. A user's role can be updated by superAdmin or admin **Rest Route** The `updateUserRole` API REST controller can be triggered via the following route: `/v1/userrole/:userId` **Rest Request Parameters** The `updateUserRole` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | roleId | String | true | request.body?.["roleId"] | **userId** : This id paremeter is used to select the required data object that will be updated **roleId** : The new roleId of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userrole/:userId** ```js axios({ method: 'PATCH', url: `/v1/userrole/${userId}`, data: { roleId:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpassword` API This route is used to update the password of users in the profile page by users themselves **Rest Route** The `updateUserPassword` API REST controller can be triggered via the following route: `/v1/userpassword/:userId` **Rest Request Parameters** The `updateUserPassword` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | oldPassword | String | true | request.body?.["oldPassword"] | | newPassword | String | true | request.body?.["newPassword"] | **userId** : This id paremeter is used to select the required data object that will be updated **oldPassword** : The old password of the user that will be overridden bu the new one. Send for double check. **newPassword** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpassword/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpassword/${userId}`, data: { oldPassword:"String", newPassword:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Userpasswordbyadmin` API This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords **Rest Route** The `updateUserPasswordByAdmin` API REST controller can be triggered via the following route: `/v1/userpasswordbyadmin/:userId` **Rest Request Parameters** The `updateUserPasswordByAdmin` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | password | String | true | request.body?.["password"] | **userId** : This id paremeter is used to select the required data object that will be updated **password** : The new password of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userpasswordbyadmin/:userId** ```js axios({ method: 'PATCH', url: `/v1/userpasswordbyadmin/${userId}`, data: { password:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Briefuser` API This route is used by public to get simple user profile information. **Rest Route** The `getBriefUser` API REST controller can be triggered via the following route: `/v1/briefuser/:userId` **Rest Request Parameters** The `getBriefUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/briefuser/:userId** ```js axios({ method: 'GET', url: `/v1/briefuser/${userId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "isActive": true } } ``` ### `Stream Test` API Test API for iterator action streaming via SSE. **Rest Route** The `streamTest` API REST controller can be triggered via the following route: `/v1/streamtest/:userId` **Rest Request Parameters** The `streamTest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/streamtest/:userId** ```js axios({ method: 'GET', url: `/v1/streamtest/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Register User` API This api is used by public users to register themselves **Rest Route** The `registerUser` API REST controller can be triggered via the following route: `/v1/registeruser` **Rest Request Parameters** The `registerUser` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | avatar | String | false | request.body?.["avatar"] | | password | String | true | request.body?.["password"] | | fullname | String | true | request.body?.["fullname"] | | email | String | true | request.body?.["email"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | **avatar** : The avatar url of the user. If not sent, a default random one will be generated. **password** : The password defined by the the user that is being registered. **fullname** : The fullname defined by the the user that is being registered. **email** : The email defined by the the user that is being registered. **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/registeruser** ```js axios({ method: 'POST', url: '/v1/registeruser', data: { avatar:"String", password:"String", fullname:"String", email:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Apply Astutor` API Authenticated user submits a tutor application. **API Frontend Description By The Backend Architect** Show a dedicated Apply as Tutor page for logged-in users. **Rest Route** The `applyAsTutor` API REST controller can be triggered via the following route: `/v1/applyastutor/:userId` **Rest Request Parameters** The `applyAsTutor` api has got 11 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/applyastutor/:userId** ```js axios({ method: 'PATCH', url: `/v1/applyastutor/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Review Tutorapplication` API **Rest Route** The `reviewTutorApplication` API REST controller can be triggered via the following route: `/v1/reviewtutorapplication/:userId` **Rest Request Parameters** The `reviewTutorApplication` api has got 11 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | fullname | String | false | request.body?.["fullname"] | | avatar | String | false | request.body?.["avatar"] | | tutorApplicationStatus | String | false | request.body?.["tutorApplicationStatus"] | | certifications | Text | false | request.body?.["certifications"] | | qualifications | Text | false | request.body?.["qualifications"] | | bio | Text | false | request.body?.["bio"] | | specializations | String | false | request.body?.["specializations"] | | applicationReviewNote | Text | false | request.body?.["applicationReviewNote"] | | applicationDocuments | String | false | request.body?.["applicationDocuments"] | | accountStatus | String | false | request.body?.["accountStatus"] | **userId** : This id paremeter is used to select the required data object that will be updated **fullname** : A string value to represent the fullname of the user **avatar** : The avatar url of the user. A random avatar will be generated if not provided **tutorApplicationStatus** : **certifications** : Tutor applicant's professional certifications. **qualifications** : Tutor applicant's educational qualifications. **bio** : Short professional bio for the tutor applicant. **specializations** : Subject areas the tutor specializes in. **applicationReviewNote** : **applicationDocuments** : URLs of uploaded documents for tutor application. **accountStatus** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/reviewtutorapplication/:userId** ```js axios({ method: 'PATCH', url: `/v1/reviewtutorapplication/${userId}`, data: { fullname:"String", avatar:"String", tutorApplicationStatus:"String", certifications:"Text", qualifications:"Text", bio:"Text", specializations:"String", applicationReviewNote:"Text", applicationDocuments:"String", accountStatus:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "tutorApplicationStatus": "String", "tutorApplicationStatus_idx": "Integer", "certifications": "Text", "qualifications": "Text", "bio": "Text", "specializations": "String", "applicationReviewNote": "Text", "applicationDocuments": "String", "accountStatus": "String", "accountStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Useravatarsfile` API **[Default get API]** — This is the designated default `get` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getUserAvatarsFile` API REST controller can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` **Rest Request Parameters** The `getUserAvatarsFile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | **userAvatarsFileId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'GET', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Useravatarsfiles` API **[Default list API]** — This is the designated default `list` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listUserAvatarsFiles` API REST controller can be triggered via the following route: `/v1/useravatarsfiles` **Rest Request Parameters** **Filter Parameters** The `listUserAvatarsFiles` api supports 3 optional filter parameters for filtering list results: **mimeType** (`String`): MIME type of the uploaded file (e.g., image/png, application/pdf). - Single (partial match, case-insensitive): `?mimeType=` - Multiple: `?mimeType=&mimeType=` - Null: `?mimeType=null` **ownerId** (`ID`): ID of the user who uploaded the file (from session). - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **userId** (`ID`): Reference to the owner user record. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles** ```js axios({ method: 'GET', url: '/v1/useravatarsfiles', data: { }, params: { // Filter parameters (see Filter Parameters section above) // mimeType: '' // Filter by mimeType // ownerId: '' // Filter by ownerId // userId: '' // Filter by userId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userAvatarsFiles": [ { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Delete Useravatarsfile` API **[Default delete API]** — This is the designated default `delete` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteUserAvatarsFile` API REST controller can be triggered via the following route: `/v1/useravatarsfiles/:userAvatarsFileId` **Rest Request Parameters** The `deleteUserAvatarsFile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] | **userAvatarsFileId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/useravatarsfiles/:userAvatarsFileId** ```js axios({ method: 'DELETE', url: `/v1/useravatarsfiles/${userAvatarsFileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userAvatarsFile", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "userAvatarsFile": { "id": "ID", "fileName": "String", "mimeType": "String", "fileSize": "Integer", "accessKey": "String", "ownerId": "ID", "fileData": "Blob", "metadata": "Object", "userId": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### Authentication Specific Routes ### Route: login *Route Definition*: Handles the login process by verifying user credentials and generating an authenticated session. *Route Type*: login *Access Routes*: - `GET /login`: Returns the HTML login page (not a frontend module, typically used in browser-based contexts for test purpose to make sending POST /login easier). - `POST /login`: Accepts credentials, verifies the user, creates a session, and returns a JWT access token. #### Parameters | Parameter | Type | Required | Population | |-------------|----------|----------|-----------------------------| | username | String | Yes | `request.body.username` | | password | String | Yes | `request.body.password` | #### Notes - This route accepts login credentials and creates an authenticated session if credentials are valid. - On success, the response will: - Set a cookie named `projectname-access-token[-tenantCodename]` with the JWT token. - Include the token in the response headers under the same name. - Return the full `session` object in the JSON body. - Note that `username` parameter should have the email of the user as value. You can also send an `email` parameter instead of `username` parameter. If both sent only `username` parameter will be read. ```js // Sample POST /login call axios.post("/login", { username: "user@example.com", password: "securePassword" }); ```` **Success Response** Returns the authenticated session object with a status code `200 OK`. A secure HTTP-only cookie and an access token header are included in the response. ```json { "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", ... } ```` **Error Responses** * **401 Unauthorized:** Invalid username or password. * **403 Forbidden:** Login attempt rejected due to pending email/mobile verification or 2FA requirements. * **400 Bad Request:** Missing credentials in the request. ### Route: logout *Route Definition*: Logs the user out by terminating the current session and clearing the access token. *Route Type*: logout *Access Route*: `POST /logout` #### Parameters This route does not require any parameters in the body or query. #### Behavior - Invalidates the current session on the server (if stored). - Clears the access token cookie (`projectname-access-token[-tenantCodename]`) from the client. - Responds with a 200 status and a simple confirmation object. ```js // Sample POST /logout call axios.post("/logout", {}, { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Notes** * This route is public, meaning it can be called without a session or token. * If the session is active, the server will clear associated session state and cookies. * The logout behavior may vary slightly depending on whether you're using cookie-based or header-based token management. **Error Responses** 00200 OK:** Always returned, regardless of whether a session existed. Logout is treated as idempotent. ### Route: publickey *Route Definition*: Returns the public RSA key used to verify JWT access tokens issued by the auth service. *Route Type*: publicKeyFetch *Access Route*: `GET /publickey` #### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|--------------------| | keyId | String | No | `request.query.keyId` | - `keyId` is optional. If provided, retrieves the public key corresponding to the specific `keyId`. If omitted, retrieves the current active public key (`global.currentKeyId`). #### Behavior - Reads the requested RSA public key file from the server filesystem. - If the key exists, returns it along with its `keyId`. - If the key does not exist, returns a 404 error. ```js // Sample GET /publickey call axios.get("/publickey", { params: { keyId: "currentKeyIdOptional" } }); ```` **Success Response** Returns the active public key and its associated keyId. ```json { "keyId": "a1b2c3d4", "keyData": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhki...\n-----END PUBLIC KEY-----" } ```` **Error Responses** **404 Not Found:** Public key file could not be found on the server. ### Token Key Management Mindbricks uses RSA key pairs to sign and verify JWT access tokens securely. While the auth service signs each token with a private key, other services within the system — or external clients — need the corresponding **public key** to verify the authenticity and integrity of received tokens. The `/publickey` endpoint allows services and clients to dynamically fetch the currently active public key, ensuring that token verification remains secure even if key rotation is performed. > **Note**: > The `/publickey` route is not intended for direct frontend (browser) consumption. > Instead, it is primarily used by trusted backend services, APIs, or middleware systems that need to independently verify access tokens issued by the auth service — without making verification-dependent API calls to the auth service itself. Accessing the public key is crucial for validating user sessions efficiently and maintaining a decentralized trust model across your platform. ### Route: relogin *Route Definition*: Performs a silent login by verifying the current access token, refreshing the session, and returning a new access token along with updated user information. *Route Type*: sessionRefresh *Access Route*: `GET /relogin` #### Parameters This route does **not** require any request parameters. #### Behavior - Validates the access token associated with the request. - If the token is valid: - Re-authenticates the user using the session's user ID. - Fetches the most up-to-date user information from the database. - Generates a new session object with a **new session ID** and **new access token**. - If the token is invalid or missing, returns a 401 Unauthorized error. ```js // Example call to refresh session axios.get("/relogin", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns a new session object, refreshed from database data. ```json { "sessionId": "new-session-uuid", "userId": "user-uuid", "email": "user@example.com", "roleId": "admin", "accessToken": "new-jwt-token", ... } ```` **Error Responses** * **401 Unauthorized**: Token is missing, invalid, or session cannot be re-established. ```json { "status": "ERR", "message": "Cannot relogin" } ```` **Notes** - The `/relogin` route is commonly used for **silent login flows**, especially after page reloads or token-based auto-login mechanisms. - It triggers internal logic (`req.userAuthUpdate = true`) to signal that the session should be re-initialized and repopulated. - It is not a simple session lookup — it performs a fresh authentication pass using the session's user context. - The refreshed session ensures any updates to user profile, roles, or permissions are immediately reflected. > **Tip:** > This route is ideal when you want to **rebuild a user's session** in the frontend without requiring them to manually log in again. ## Verification Services — Email Verification Email verification is a two-step flow that ensures a user's email address is verified and trusted by the system. All verification services, including email verification, are located under the `/verification-services` base path. ### When is Email Verification Triggered? - After user registration, if `emailVerificationRequiredForLogin` is active. - During a separate user action to verify or update email addresses. - When login fails with `EmailVerificationNeeded` and frontend initiates verification. ### Email Verification Flow 1. **Frontend calls `/verification-services/email-verification/start`** with the user's email address. - Mindbricks checks if the email is already verified. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's email or returned in the response (only in development environments for easier testing). 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/email-verification/complete`** with the `email` and the received `secretCode`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s `emailVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/email-verification/start` **Purpose** Starts the email verification process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------| | email | String | Yes | The email address to verify | ```json { "email": "user@example.com" } ```` #### Success Response Secret code details (in development environment). Confirms that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` > ⚠️ In production, the secret code is only sent via email, not exposed in the API response. #### Error Responses - `400 Bad Request`: Email already verified. - `403 Forbidden`: Sending a code too frequently (anti-spam). --- ### POST `/verification-services/email-verification/complete` **Purpose** Completes the email verification by validating the secret code. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------| | email | String | Yes | The user email being verified | | secretCode | String | Yes | The secret code received via email | ```json { "email": "user@example.com", "secretCode": "123456" } ```` #### Success Response Returns confirmation that the email has been verified. ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ```` #### Error Responses - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes ### Resend Throttling You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds). ### Expiration Handling Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day). ### One Code Per Session Only one active verification session per user is allowed at a time. > 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps. ## Verification Services — Mobile Verification Mobile verification is a two-step flow that ensures a user's mobile number is verified and trusted by the system. All verification services, including mobile verification, are located under the `/verification-services` base path. ### When is Mobile Verification Triggered? - After user registration, if `mobileVerificationRequiredForLogin` is active. - During a separate user action to verify or update mobile numbers. - When login fails with `MobileVerificationNeeded` and frontend initiates verification. ### Mobile Verification Flow 1. **Frontend calls `/verification-services/mobile-verification/start`** with the user's email address (used to locate the user). - Mindbricks checks if the mobile number is already verified. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's mobile via SMS or returned in the response (only in development environments for easier testing). 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/mobile-verification/complete`** with the `email` and the received `secretCode`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s `mobileVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/mobile-verification/start` **Purpose**: Starts the mobile verification process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address associated with the mobile number to verify | ```json { "email": "user@example.com" } ```` **Success Response** Secret code details (in development environment). Confirms that the verification step has been started. ```json { "userId": "user-uuid", "mobile": "+15551234567", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the secret code is only sent via SMS, not exposed in the API response. **Error Responses** - 400 Bad Request: Mobile already verified. - 403 Forbidden: Sending a code too frequently (anti-spam). --- ### POST `/verification-services/mobile-verification/complete` **Purpose**: Completes the mobile verification by validating the secret code. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|------------------------------------| | email | String | Yes | The user's email being verified | | secretCode | String | Yes | The secret code received via SMS | ```json { "email": "user@example.com", "secretCode": "123456" } ```` **Success Response** Returns confirmation that the mobile number has been verified. ```json { "userId": "user-uuid", "mobile": "+15551234567", "isVerified": true } ```` **Error Responses** 403 Forbidden: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes **Resend Throttling**: You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds). **Expiration Handling**: Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day). **One Code Per Session**: Only one active verification session per user is allowed at a time. 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps. ## Verification Services — Email 2FA Verification Email 2FA (Two-Factor Authentication) provides an additional layer of security by requiring users to confirm their identity using a secret code sent to their email address. This process is used in login flows or sensitive actions that need extra verification. All verification services, including 2FA, are located under the `/verification-services` base path. ### When is Email 2FA Triggered? - During login flows where `sessionNeedsEmail2FA` is `true` - When the backend enforces two-factor authentication for a sensitive operation ### Email 2FA Flow 1. **Frontend calls `/verification-services/email-2factor-verification/start`** with the user's id, session id, client info, and reason. - Mindbricks identifies the user and checks if a cooldown period applies. - A new secret code is generated and stored, linked to the current session ID. - The code is sent via email or returned in development environments. 2. **User receives the code and enters it into the frontend application.** 3. **Frontend calls `/verification-services/email-2factor-verification/complete`** with the `userId`, `sessionId`, and the `secretCode`. - Mindbricks verifies the code, validates the session, and updates the session to remove the 2FA requirement. --- ## API Endpoints ### POST `/verification-services/email-2factor-verification/start` **Purpose**: Starts the email-based 2FA process by generating and sending a verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The current session ID | | client | String | No | Optional client tag or context | | reason | String | No | Optional reason for triggering 2FA | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "client": "login-page", "reason": "Login requires email 2FA" } ```` #### Success Response ```json { "sessionId": "session-uuid", "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 300, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the `secretCode` is only sent via email, not exposed in the API response. #### Error Responses - **403 Forbidden**: Sending a code too frequently (anti-spam) - **401 Unauthorized**: User session not found --- ### POST `/verification-services/email-2factor-verification/complete` **Purpose**: Completes the email 2FA process by validating the secret code and session. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|--------------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The session ID the code is tied to | | secretCode | String | Yes | The secret code received via email | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "secretCode": "123456" } ```` #### Success Response Returns an updated session with 2FA disabled: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "sessionNeedsEmail2FA": false, ... } ```` #### Error Responses - **403 Forbidden**: - Secret code mismatch - Secret code expired - Verification step not found --- ### Important Behavioral Notes - **One Code Per Session**: Only one active code can be issued per session. - **Resend Throttling**: Code requests are throttled based on `resendTimeWindow` (e.g., 60 seconds). - **Expiration**: Codes expire after `expireTimeWindow` (e.g., 5 minutes). - 💡 Mindbricks manages session cache, spam control, expiration tracking, and event notifications for all 2FA steps. ## Verification Services — Mobile 2FA Verification Mobile 2FA (Two-Factor Authentication) is a security mechanism that adds an extra layer of authentication using a user's verified mobile number. All verification services, including mobile 2FA, are accessible under the `/verification-services` base path. ### When is Mobile 2FA Triggered? - During login or critical actions requiring step-up authentication. - When the session has a flag `sessionNeedsMobile2FA = true`. - When login or session verification fails with `MobileVerificationNeeded`, indicating 2FA is required. ### Mobile 2FA Verification Flow 1. **Frontend calls `/verification-services/mobile-2factor-verification/start`** with the user's id, session id, client info, and reason. - Mindbricks finds the user by id. - Verifies that the user has a verified mobile number. - A secret code is generated and cached against the session. - The code is sent to the user's verified mobile number or returned in the response (only in development environments). 2. **User receives the code and enters it in the frontend app.** 3. **Frontend calls `/verification-services/mobile-2factor-verification/complete`** with the `userId`, `sessionId`, and `secretCode`. - Mindbricks validates the code for expiration and correctness. - If valid, the session flag `sessionNeedsMobile2FA` is cleared. - A refreshed session object is returned. --- ## API Endpoints ### POST `/verification-services/mobile-2factor-verification/start` **Purpose**: Initiates mobile-based 2FA by generating and sending a secret code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-----------------------------------------------| | userId | String | Yes | The user’s ID | | sessionId | String | Yes | The current session ID | | client | String | No | Optional client tag or context | | reason | String | No | Optional reason for triggering 2FA | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "client": "login-page", "reason": "Login requires mobile 2FA" } ```` **Success Response** Returns the generated code (only in development), expiration info, and metadata. ```json { "userId": "user-uuid", "sessionId": "session-uuid", "mobile": "+15551234567", "secretCode": "654321", "expireTime": 300, "date": "2024-04-29T11:00:00.000Z" } ```` ⚠️ In production environments, the secret code is not included in the response and is instead delivered via SMS. **Error Responses** - 403 Forbidden: Mobile number not verified. - 403 Forbidden: Code resend attempted before cooldown period (`resendTimeWindow`). - 401 Unauthorized: Email not recognized or session invalid. --- ### POST `/verification-services/mobile-2factor-verification/complete` **Purpose**: Completes mobile 2FA verification by validating the secret code and updating the session. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------| | userId | String | Yes | ID of the user | | sessionId | String | Yes | ID of the session | | secretCode | String | Yes | The 6-digit code received via SMS | ```json { "userId": "user-uuid", "sessionId": "session-uuid", "secretCode": "654321" } ```` **Success Response** Returns the updated session with `sessionNeedsMobile2FA: false`. ```json { "sessionId": "session-uuid", "userId": "user-uuid", "sessionNeedsMobile2FA": false, "accessToken": "jwt-token", "expiresIn": 86400 } ```` **Error Responses** - 403 Forbidden: Code mismatch or expired. - 403 Forbidden: No ongoing verification found. - 401 Unauthorized: Session does not exist or is invalid. --- ### Behavioral Notes - **Rate Limiting**: A user can only request a new mobile 2FA code after the cooldown period (`resendTimeWindow`, e.g., 60 seconds). - **Expiration**: Mobile 2FA codes expire after the configured time (`expireTimeWindow`, e.g., 5 minutes). - **Session Integrity**: Verification status is tied to the session; incorrect sessionId will invalidate the attempt. 💡 Mindbricks handles session integrity, rate limiting, and secure code delivery to ensure a robust mobile 2FA process. ## Verification Services — Password Reset by Email Password Reset by Email enables a user to securely reset their password using a secret code sent to their registered email address. All verification services, including password reset by email, are located under the `/verification-services` base path. ### When is Password Reset by Email Triggered? - When a user requests to reset their password by providing their email address. - This service is typically exposed on a “Forgot Password?” flow in the frontend. ### Password Reset Flow 1. **Frontend calls `/verification-services/password-reset-by-email/start`** with the user's email. - Mindbricks checks if the user exists and if the email is registered. - A secret code is generated and stored in the cache linked to the user. - The code is sent to the user's email, or returned in the response (in development environments only for testing). 2. **User receives the code and enters it into the frontend along with the new password.** 3. **Frontend calls `/verification-services/password-reset-by-email/complete`** with the `email`, the `secretCode`, and the new `password`. - Mindbricks checks that the code is valid, not expired, and matches. - If valid, the user’s password is reset, their `emailVerified` flag is set to `true`, and a success response is returned. --- ## API Endpoints ### POST `/verification-services/password-reset-by-email/start` **Purpose**: Starts the password reset process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address of the user | ```json { "email": "user@example.com" } ```` **Success Response** Returns secret code details (only in development environment) and confirmation that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the secret code is only sent via email and not exposed in the API response. **Error Responses** - `401 NotAuthenticated`: Email address not found or not associated with a user. - `403 Forbidden`: Sending a code too frequently (spam prevention). --- ### POST `/verification-services/password-reset-by-email/complete` **Purpose**: Completes the password reset process by validating the secret code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|----------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via email | | password | String | Yes | The new password the user wants to set | ```json { "email": "user@example.com", "secretCode": "123456", "password": "newSecurePassword123" } ```` **Success Response** ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ```` **Error Responses** - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Important Behavioral Notes ### Resend Throttling: A new verification code can only be requested after a cooldown period (configured via `resendTimeWindow`, e.g., 60 seconds). ### Expiration Handling: Verification codes automatically expire after a predefined period (`expireTimeWindow`, e.g., 1 day). ### Session & Event Handling: Mindbricks manages: - Spam prevention - Code caching per user - Expiration logic - Verification start/complete events ## Verification Services — Password Reset by Mobile Password reset by mobile provides users with a secure mechanism to reset their password using a verification code sent via SMS to their registered mobile number. All verification services, including password reset by mobile, are located under the `/verification-services` base path. ### When is Password Reset by Mobile Triggered? - When a user forgets their password and selects the mobile reset option. - When a user explicitly initiates password recovery via mobile on the login or help screen. ### Password Reset by Mobile Flow 1. **Frontend calls `/verification-services/password-reset-by-mobile/start`** with the user's mobile number or associated identifier. - Mindbricks checks if a user with the given mobile exists. - A secret code is generated and stored in the cache for that user. - The code is sent to the user's mobile (or returned in development environments for testing). 2. **User receives the code via SMS and enters it into the frontend app.** 3. **Frontend calls `/verification-services/password-reset-by-mobile/complete`** with the user's `email`, the `secretCode`, and the new `password`. - Mindbricks validates the secret code and its expiration. - If valid, it updates the user's password and returns a success response. --- ## API Endpoints ### POST `/verification-services/password-reset-by-mobile/start` **Purpose**: Initiates the mobile-based password reset by sending a verification code to the user's mobile. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|------------------------------| | mobile | String | Yes | The mobile number to verify | ```json { "mobile": "+905551234567" } ```` ### Success Response Returns the verification context (code returned only in development): ```json { "userId": "user-uuid", "mobile": "+905551234567", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z" } ```` ⚠️ In production, the `secretCode` is not included in the response and is only sent via SMS. ### Error Responses - **400 Bad Request**: Mobile already verified - **403 Forbidden**: Rate-limited (code already sent recently) - **404 Not Found**: User with provided mobile not found --- ### POST `/verification-services/password-reset-by-mobile/complete` **Purpose**: Finalizes the password reset process by validating the received verification code and updating the user’s password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via SMS | | password | String | Yes | The new password to assign | ```json { "email": "user@example.com", "secretCode": "123456", "password": "NewSecurePassword123!" } ```` ### Success Response ```json { "userId": "user-uuid", "mobile": "+905551234567", "isVerified": true } ```` --- ### Important Behavioral Notes - **Throttling**: Codes can only be resent after a delay defined by `resendTimeWindow` (e.g., 60 seconds). - **Expiration**: Codes expire after the `expireTimeWindow` (e.g., 1 day). - **One Active Session**: Only one active password reset session is allowed per user at a time. - **Session-less**: This flow does not require an active session — it works for unauthenticated users. 💡 Mindbricks handles spam protection, session caching, and event-based logging (for both start and complete operations) as part of the verification service base class. ## Verification Method Types ### 🧾 For byCode Verifications This verification type requires the user to manually enter a 6-digit code. **Frontend Action**: Display a secure input page where the user can enter the code they received via email or SMS. After collecting the code and any required metadata (such as `userId` or `sessionId`), make a `POST` request to the corresponding `/complete` endpoint. --- ### 🔗 For byLink Verifications This verification type uses a clickable link embedded in an email (or SMS message). **Frontend Action**: The link points to a `GET` page in your frontend that parses `userId` and `code` from the query string and sends them to the backend via a `POST` request to the corresponding `/complete` endpoint. This enables one-click verification without requiring the user to type in a code. ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## tutorhub-tutorcatalog-service **Version:** `1.0.45` Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the TutorCatalog Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our TutorCatalog Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the TutorCatalog Service via HTTP requests for purposes such as creating, updating, deleting and querying TutorCatalog objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the TutorCatalog Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the TutorCatalog service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the TutorCatalog service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the TutorCatalog service. This service is configured to listen for HTTP requests on port `3000`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/tutorcatalog-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/tutorcatalog-api` * **Production:** `https://tutorhub.mindbricks.co/tutorcatalog-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the TutorCatalog service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `TutorCatalog` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `TutorCatalog` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `TutorCatalog` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources TutorCatalog service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### TutorProfile resource *Resource Definition* : Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. *TutorProfile Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **tutorId** | ID | | | ** | | **certifications** | String | | | *Tutor's certifications (list of certificates, degrees, etc.).* | | **experience** | Text | | | *Brief experience summary or bio.* | | **subjects** | String | | | *Areas of expertise/subjects offered for teaching.* | | **bio** | Text | | | *Optional full-length bio/description.* | | **profilePhoto** | String | | | *Public profile photo URL (may be external or uploaded).* | | **profileStatus** | Enum | | | ** | | **displayName** | String | | | *Tutor's display name, copied from auth user fullname at profile creation.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### profileStatus Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ### CoursePack resource *Resource Definition* : Publicly listed course pack/structured course offered by a tutor. *CoursePack Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **tutorProfileId** | ID | | | ** | | **title** | String | | | ** | | **description** | Text | | | ** | | **price** | Double | | | ** | | **category** | String | | | ** | | **schedulingType** | Enum | | | ** | | **minWeeklyClasses** | Integer | | | ** | | **preliminaryMeetingRequired** | Boolean | | | ** | | **isPublished** | Boolean | | | ** | | **maxDailyLessons** | Integer | | | ** | | **requiredClassesCount** | Integer | | | ** | | **moderationStatus** | Enum | | | *Content moderation status.* | | **moderationNote** | String | | | *Admin note for flagged/removed course packs.* | | **maxPeriodValue** | Integer | | | *Maximum time period value for strict scheduling (e.g. 3 for 3 months)* | | **maxPeriodUnit** | Enum | | | *Time unit for maxPeriodValue in strict scheduling* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### schedulingType Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **flexible** | `"flexible""` | 0 | | **strict** | `"strict""` | 1 | ##### moderationStatus Enum Property *Property Definition* : Content moderation status.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **approved** | `"approved""` | 0 | | **flagged** | `"flagged""` | 1 | | **removed** | `"removed""` | 2 | ##### maxPeriodUnit Enum Property *Property Definition* : Time unit for maxPeriodValue in strict scheduling*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **weeks** | `"weeks""` | 0 | | **months** | `"months""` | 1 | ### CourseMaterial resource *Resource Definition* : Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. *CourseMaterial Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to coursePack.* | | **fileUrl** | String | | | *URL for file/video/document. For downloads or video links (protected).* | | **fileType** | Enum | | | *Type: file, video, document, externalLink.* | | **title** | String | | | *Material title (unique per pack).* | | **description** | Text | | | *Additional details about the material resource.* | | **linkUrl** | String | | | *Optional URL for external resource (if fileType = externalLink).* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### fileType Enum Property *Property Definition* : Type: file, video, document, externalLink.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **file** | `"file""` | 0 | | **video** | `"video""` | 1 | | **document** | `"document""` | 2 | | **externalLink** | `"externalLink""` | 3 | ### CourseCategory resource *Resource Definition* : Represents a course subject/category; used for filtering and navigation. Admin-maintained. *CourseCategory Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **name** | String | | | *Unique category/subject name.* | | **description** | Text | | | *Category description.* | | **icon** | String | | | *Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵)* | ## Business Api ### `Create Tutorprofile` API **Rest Route** The `createTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles` **Rest Request Parameters** The `createTutorProfile` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | bio | Text | false | request.body?.["bio"] | | experience | Text | false | request.body?.["experience"] | | profileStatus | String | false | request.body?.["profileStatus"] | | certifications | String | false | request.body?.["certifications"] | | subjects | String | false | request.body?.["subjects"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | displayName | String | false | request.body?.["displayName"] | **tutorId** : ID of the auth user who is becoming a tutor **bio** : Tutor's biography **experience** : Tutor's experience/qualifications **profileStatus** : Approval status - should be 'approved' when created from auth **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **subjects** : Areas of expertise/subjects offered for teaching. **profilePhoto** : Public profile photo URL (may be external or uploaded). **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/tutorprofiles** ```js axios({ method: 'POST', url: '/v1/tutorprofiles', data: { tutorId:"ID", bio:"Text", experience:"Text", profileStatus:"String", certifications:"String", subjects:"String", profilePhoto:"String", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Tutorprofile` API **[Default update API]** — This is the designated default `update` API for the `tutorProfile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates their own profile. Only owner tutor or admin can update. **Rest Route** The `updateTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` **Rest Request Parameters** The `updateTutorProfile` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | | tutorId | ID | false | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | false | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | **tutorProfileId** : This id paremeter is used to select the required data object that will be updated **tutorId** : **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **experience** : Brief experience summary or bio. **subjects** : Areas of expertise/subjects offered for teaching. **bio** : Optional full-length bio/description. **profilePhoto** : Public profile photo URL (may be external or uploaded). **profileStatus** : **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/tutorprofiles/:tutorProfileId** ```js axios({ method: 'PATCH', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Tutorprofile` API **[Default get API]** — This is the designated default `get` API for the `tutorProfile` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly get a tutor profile by ID. No login required. **Rest Route** The `getTutorProfile` API REST controller can be triggered via the following route: `/v1/tutorprofiles/:tutorProfileId` **Rest Request Parameters** The `getTutorProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | **tutorProfileId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/tutorprofiles/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/tutorprofiles/${tutorProfileId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Tutorprofiles` API **Rest Route** The `listTutorProfiles` API REST controller can be triggered via the following route: `/v1/tutorprofiles` **Rest Request Parameters** The `listTutorProfiles` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/tutorprofiles** ```js axios({ method: 'GET', url: '/v1/tutorprofiles', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfiles", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "tutorProfiles": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursepack` API **[Default create API]** — This is the designated default `create` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor creates a new course offering. Only accessible to tutors (or admin, for moderation). **Rest Route** The `createCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks` **Rest Request Parameters** The `createCoursePack` api has got 14 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | true | request.body?.["price"] | | category | String | true | request.body?.["category"] | | schedulingType | Enum | true | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | true | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | true | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | **tutorProfileId** : **title** : **description** : **price** : **category** : **schedulingType** : **minWeeklyClasses** : **preliminaryMeetingRequired** : **isPublished** : **maxDailyLessons** : **requiredClassesCount** : **moderationNote** : Admin note for flagged/removed course packs. **maxPeriodValue** : Maximum time period value for strict scheduling (e.g. 3 for 3 months) **maxPeriodUnit** : Time unit for maxPeriodValue in strict scheduling **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursepacks** ```js axios({ method: 'POST', url: '/v1/coursepacks', data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursepack` API **[Default update API]** — This is the designated default `update` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates their course pack. Only owner tutor or admin can update. Ownership is verified via tutorProfile and user session. **Rest Route** The `updateCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `updateCoursePack` api has got 16 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | price | Double | false | request.body?.["price"] | | category | String | false | request.body?.["category"] | | schedulingType | Enum | false | request.body?.["schedulingType"] | | minWeeklyClasses | Integer | false | request.body?.["minWeeklyClasses"] | | preliminaryMeetingRequired | Boolean | false | request.body?.["preliminaryMeetingRequired"] | | isPublished | Boolean | false | request.body?.["isPublished"] | | maxDailyLessons | Integer | false | request.body?.["maxDailyLessons"] | | requiredClassesCount | Integer | false | request.body?.["requiredClassesCount"] | | moderationStatus | Enum | false | request.body?.["moderationStatus"] | | moderationNote | String | false | request.body?.["moderationNote"] | | maxPeriodValue | Integer | false | request.body?.["maxPeriodValue"] | | maxPeriodUnit | Enum | false | request.body?.["maxPeriodUnit"] | **coursePackId** : This id paremeter is used to select the required data object that will be updated **tutorProfileId** : **title** : **description** : **price** : **category** : **schedulingType** : **minWeeklyClasses** : **preliminaryMeetingRequired** : **isPublished** : **maxDailyLessons** : **requiredClassesCount** : **moderationStatus** : Content moderation status. **moderationNote** : Admin note for flagged/removed course packs. **maxPeriodValue** : Maximum time period value for strict scheduling (e.g. 3 for 3 months) **maxPeriodUnit** : Time unit for maxPeriodValue in strict scheduling **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursepacks/:coursePackId** ```js axios({ method: 'PATCH', url: `/v1/coursepacks/${coursePackId}`, data: { tutorProfileId:"ID", title:"String", description:"Text", price:"Double", category:"String", schedulingType:"Enum", minWeeklyClasses:"Integer", preliminaryMeetingRequired:"Boolean", isPublished:"Boolean", maxDailyLessons:"Integer", requiredClassesCount:"Integer", moderationStatus:"Enum", moderationNote:"String", maxPeriodValue:"Integer", maxPeriodUnit:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursepack` API **[Default delete API]** — This is the designated default `delete` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes their course pack. Only owner tutor or admin can delete. Tutors are blocked if active enrollments exist. Admin can force-delete with a reason, which triggers pro-rata refunds and student notifications. **API Frontend Description By The Backend Architect** Tutors cannot delete a course with active enrollments — they should unpublish instead. Admin can force-delete with a mandatory reason; this triggers automatic pro-rata refunds and email notifications to affected students. **Rest Route** The `deleteCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `deleteCoursePack` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | | removalReason | String | | request.body?.["removalReason"] | **coursePackId** : This id paremeter is used to select the required data object that will be deleted **removalReason** : Required when admin deletes a course with active enrollments. Reason is sent to affected students via email. **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/coursepacks/:coursePackId** ```js axios({ method: 'DELETE', url: `/v1/coursepacks/${coursePackId}`, data: { removalReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "coursePack": { "id": "ID", "tutorProfileId": "ID", "title": "String", "description": "Text", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "minWeeklyClasses": "Integer", "preliminaryMeetingRequired": "Boolean", "isPublished": "Boolean", "maxDailyLessons": "Integer", "requiredClassesCount": "Integer", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "moderationNote": "String", "maxPeriodValue": "Integer", "maxPeriodUnit": "Enum", "maxPeriodUnit_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursepack` API **[Default get API]** — This is the designated default `get` API for the `coursePack` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly get a course pack by ID. No login required. **Rest Route** The `getCoursePack` API REST controller can be triggered via the following route: `/v1/coursepacks/:coursePackId` **Rest Request Parameters** The `getCoursePack` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.params?.["coursePackId"] | **coursePackId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursepacks/:coursePackId** ```js axios({ method: 'GET', url: `/v1/coursepacks/${coursePackId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePack", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "coursePack": { "tutorProfile": { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, "isActive": true } } ``` ### `List Coursepacks` API **Rest Route** The `listCoursePacks` API REST controller can be triggered via the following route: `/v1/coursepacks` **Rest Request Parameters** The `listCoursePacks` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursepacks** ```js axios({ method: 'GET', url: '/v1/coursepacks', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "coursePacks", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "coursePacks": [ { "tutorProfile": [ { "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "displayName": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursematerial` API **[Default create API]** — This is the designated default `create` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor uploads a material to a course pack they own. Only tutor or admin can create. **Rest Route** The `createCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials` **Rest Request Parameters** The `createCourseMaterial` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | fileUrl | String | true | request.body?.["fileUrl"] | | fileType | Enum | true | request.body?.["fileType"] | | title | String | true | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | **coursePackId** : FK to coursePack. **fileUrl** : URL for file/video/document. For downloads or video links (protected). **fileType** : Type: file, video, document, externalLink. **title** : Material title (unique per pack). **description** : Additional details about the material resource. **linkUrl** : Optional URL for external resource (if fileType = externalLink). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursematerials** ```js axios({ method: 'POST', url: '/v1/coursematerials', data: { coursePackId:"ID", fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursematerial` API **[Default update API]** — This is the designated default `update` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates course material. Only course's tutor or admin can update. **Rest Route** The `updateCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `updateCourseMaterial` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | | fileUrl | String | false | request.body?.["fileUrl"] | | fileType | Enum | false | request.body?.["fileType"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | linkUrl | String | false | request.body?.["linkUrl"] | **courseMaterialId** : This id paremeter is used to select the required data object that will be updated **fileUrl** : URL for file/video/document. For downloads or video links (protected). **fileType** : Type: file, video, document, externalLink. **title** : Material title (unique per pack). **description** : Additional details about the material resource. **linkUrl** : Optional URL for external resource (if fileType = externalLink). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'PATCH', url: `/v1/coursematerials/${courseMaterialId}`, data: { fileUrl:"String", fileType:"Enum", title:"String", description:"Text", linkUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursematerial` API **[Default delete API]** — This is the designated default `delete` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes course material. Only course's tutor or admin can delete. **Rest Route** The `deleteCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `deleteCourseMaterial` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | **courseMaterialId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'DELETE', url: `/v1/coursematerials/${courseMaterialId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "id": "ID", "coursePackId": "ID", "fileUrl": "String", "fileType": "Enum", "fileType_idx": "Integer", "title": "String", "description": "Text", "linkUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursematerial` API **[Default get API]** — This is the designated default `get` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get course material. Only accessible by tutor owner or enrolled student or admin. **Rest Route** The `getCourseMaterial` API REST controller can be triggered via the following route: `/v1/coursematerials/:courseMaterialId` **Rest Request Parameters** The `getCourseMaterial` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseMaterialId | ID | true | request.params?.["courseMaterialId"] | **courseMaterialId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursematerials/:courseMaterialId** ```js axios({ method: 'GET', url: `/v1/coursematerials/${courseMaterialId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterial", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseMaterial": { "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` ### `List Coursematerials` API **[Default list API]** — This is the designated default `list` API for the `courseMaterial` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List course materials for a coursePack. Only accessible to enrolled students, tutor owner, or admin. **Rest Route** The `listCourseMaterials` API REST controller can be triggered via the following route: `/v1/coursematerials` **Rest Request Parameters** The `listCourseMaterials` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursematerials** ```js axios({ method: 'GET', url: '/v1/coursematerials', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseMaterials", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseMaterials": [ { "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Coursecategory` API **[Default create API]** — This is the designated default `create` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin creates new course category/subject tag. **Rest Route** The `createCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories` **Rest Request Parameters** The `createCourseCategory` api has got 3 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | **name** : Unique category/subject name. **description** : Category description. **icon** : Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/coursecategories** ```js axios({ method: 'POST', url: '/v1/coursecategories', data: { name:"String", description:"Text", icon:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Coursecategory` API **[Default update API]** — This is the designated default `update` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin updates course category/subject tag. **Rest Route** The `updateCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` **Rest Request Parameters** The `updateCourseCategory` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | | name | String | false | request.body?.["name"] | | description | Text | false | request.body?.["description"] | | icon | String | false | request.body?.["icon"] | **courseCategoryId** : This id paremeter is used to select the required data object that will be updated **name** : Unique category/subject name. **description** : Category description. **icon** : Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/coursecategories/:courseCategoryId** ```js axios({ method: 'PATCH', url: `/v1/coursecategories/${courseCategoryId}`, data: { name:"String", description:"Text", icon:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Coursecategory` API **[Default delete API]** — This is the designated default `delete` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin deletes a course category/subject tag. Only admin allowed. **Rest Route** The `deleteCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:courseCategoryId` **Rest Request Parameters** The `deleteCourseCategory` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | courseCategoryId | ID | true | request.params?.["courseCategoryId"] | **courseCategoryId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/coursecategories/:courseCategoryId** ```js axios({ method: 'DELETE', url: `/v1/coursecategories/${courseCategoryId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "courseCategory": { "id": "ID", "name": "String", "description": "Text", "icon": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Coursecategory` API **[Default get API]** — This is the designated default `get` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly fetch a course category/subject by name. No login required. **Rest Route** The `getCourseCategory` API REST controller can be triggered via the following route: `/v1/coursecategories/:name` **Rest Request Parameters** The `getCourseCategory` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | name | String | true | request.params?.["name"] | **name** : Unique category/subject name.. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursecategories/:name** ```js axios({ method: 'GET', url: `/v1/coursecategories/${name}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategory", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "courseCategory": { "isActive": true } } ``` ### `List Coursecategories` API **[Default list API]** — This is the designated default `list` API for the `courseCategory` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Publicly list all course categories/subjects for navigation, filtering, and display. No login required. **Rest Route** The `listCourseCategories` API REST controller can be triggered via the following route: `/v1/coursecategories` **Rest Request Parameters** The `listCourseCategories` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/coursecategories** ```js axios({ method: 'GET', url: '/v1/coursecategories', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "courseCategories", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "courseCategories": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `On Tutorapplicationreviewed` API **API Frontend Description By The Backend Architect** Kafka event handler that creates tutor profile when auth service approves a tutor application. Listens to tutorhub-auth-service-tutorapplication-reviewed topic. **Rest Route** The `onTutorApplicationReviewed` API REST controller can be triggered via the following route: `/v1/ontutorapplicationreviewed` **Rest Request Parameters** The `onTutorApplicationReviewed` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorId | ID | true | request.body?.["tutorId"] | | certifications | String | false | request.body?.["certifications"] | | experience | Text | false | request.body?.["experience"] | | subjects | String | false | request.body?.["subjects"] | | bio | Text | false | request.body?.["bio"] | | profilePhoto | String | false | request.body?.["profilePhoto"] | | profileStatus | Enum | true | request.body?.["profileStatus"] | | displayName | String | false | request.body?.["displayName"] | **tutorId** : **certifications** : Tutor's certifications (list of certificates, degrees, etc.). **experience** : Brief experience summary or bio. **subjects** : Areas of expertise/subjects offered for teaching. **bio** : Optional full-length bio/description. **profilePhoto** : Public profile photo URL (may be external or uploaded). **profileStatus** : **displayName** : Tutor's display name, copied from auth user fullname at profile creation. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/ontutorapplicationreviewed** ```js axios({ method: 'POST', url: '/v1/ontutorapplicationreviewed', data: { tutorId:"ID", certifications:"String", experience:"Text", subjects:"String", bio:"Text", profilePhoto:"String", profileStatus:"Enum", displayName:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "tutorProfile", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "tutorProfile": { "id": "ID", "tutorId": "ID", "certifications": "String", "experience": "Text", "subjects": "String", "bio": "Text", "profilePhoto": "String", "profileStatus": "Enum", "profileStatus_idx": "Integer", "displayName": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## tutorhub-coursescheduling-service **Version:** `1.0.48` Handles all scheduling: tutor availability, lesson slot management/booking, preliminary meeting scheduling for screened courses. Ensures schedule privacy (authenticated only). ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the CourseScheduling Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our CourseScheduling Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the CourseScheduling Service via HTTP requests for purposes such as creating, updating, deleting and querying CourseScheduling objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the CourseScheduling Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the CourseScheduling service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the CourseScheduling service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the CourseScheduling service. This service is configured to listen for HTTP requests on port `3002`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/coursescheduling-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/coursescheduling-api` * **Production:** `https://tutorhub.mindbricks.co/coursescheduling-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the CourseScheduling service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `CourseScheduling` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `CourseScheduling` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `CourseScheduling` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources CourseScheduling service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### Availability resource *Resource Definition* : Weekly availability window for a tutor, determines open slots for student booking. Each tuple is for a specific day/time window. *Availability Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **tutorProfileId** | ID | | | *FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit.* | | **dayOfWeek** | Enum | | | *Day of week: sunday-saturday.* | | **startTime** | String | | | *Start time of window (HH:mm, 24h).* | | **endTime** | String | | | *End time of window (HH:mm, 24h).* | | **isRecurring** | Boolean | | | *If true, this slot recurs weekly.* | | **specificDate** | Date | | | *Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots.* | | **teachingMode** | Enum | | | ** | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### dayOfWeek Enum Property *Property Definition* : Day of week: sunday-saturday.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **sunday** | `"sunday""` | 0 | | **monday** | `"monday""` | 1 | | **tuesday** | `"tuesday""` | 2 | | **wednesday** | `"wednesday""` | 3 | | **thursday** | `"thursday""` | 4 | | **friday** | `"friday""` | 5 | | **saturday** | `"saturday""` | 6 | ##### teachingMode Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **online** | `"online""` | 0 | | **faceToFace** | `"faceToFace""` | 1 | | **both** | `"both""` | 2 | ### LessonSlot resource *LessonSlot Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view.* | | **studentId** | ID | | | *FK to auth:user (student). Set on booking. Nullable when open (free).* | | **scheduledDate** | Date | | | *Date for the lesson slot (yyyy-mm-dd).* | | **scheduledTime** | String | | | *Start time of lesson (HH:mm 24h).* | | **status** | Enum | | | *State of lesson slot (free, booked, completed, canceled).* | | **locationType** | Enum | | | ** | | **locationDetails** | String | | | *Optional: Location address/details; editable after booking by either party.* | | **sessionMode** | Enum | | | *Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails.* | | **meetLink** | String | | | *Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Property Definition* : State of lesson slot (free, booked, completed, canceled).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **free** | `"free""` | 0 | | **booked** | `"booked""` | 1 | | **completed** | `"completed""` | 2 | | **canceled** | `"canceled""` | 3 | ##### locationType Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **online** | `"online""` | 0 | | **studentHome** | `"studentHome""` | 1 | | **tutorHome** | `"tutorHome""` | 2 | | **other** | `"other""` | 3 | ##### sessionMode Enum Property *Property Definition* : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **online** | `"online""` | 0 | | **faceToFace** | `"faceToFace""` | 1 | ### PreliminaryMeeting resource *Resource Definition* : Request for a pre-enrollment screening meeting with a tutor, required for some advanced coursePacks. *PreliminaryMeeting Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to tutorCatalog:coursePack (the advanced course)* | | **studentId** | ID | | | *FK to auth:user (student who requested).* | | **scheduledDatetime** | Date | | | *Datetime for screening meeting; may be null until both parties agree.* | | **tutorDecision** | Enum | | | ** | | **comments** | String | | | *Optional field for tutor to provide comments/notes about screening result.* | | **meetingLink** | String | | | *Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### tutorDecision Enum Property *Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ## Business Api ### `Create Availability` API **[Default create API]** — This is the designated default `create` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor creates available time window for teaching. Only owner tutor or admin. **Rest Route** The `createAvailability` API REST controller can be triggered via the following route: `/v1/availabilities` **Rest Request Parameters** The `createAvailability` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | dayOfWeek | Enum | true | request.body?.["dayOfWeek"] | | startTime | String | true | request.body?.["startTime"] | | endTime | String | true | request.body?.["endTime"] | | isRecurring | Boolean | true | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | true | request.body?.["teachingMode"] | **tutorProfileId** : FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit. **dayOfWeek** : Day of week: sunday-saturday. **startTime** : Start time of window (HH:mm, 24h). **endTime** : End time of window (HH:mm, 24h). **isRecurring** : If true, this slot recurs weekly. **specificDate** : Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. **teachingMode** : **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/availabilities** ```js axios({ method: 'POST', url: '/v1/availabilities', data: { tutorProfileId:"ID", dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Availability` API **[Default update API]** — This is the designated default `update` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates an availability record (only own, or admin). **Rest Route** The `updateAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `updateAvailability` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | | dayOfWeek | Enum | false | request.body?.["dayOfWeek"] | | startTime | String | false | request.body?.["startTime"] | | endTime | String | false | request.body?.["endTime"] | | isRecurring | Boolean | false | request.body?.["isRecurring"] | | specificDate | Date | false | request.body?.["specificDate"] | | teachingMode | Enum | false | request.body?.["teachingMode"] | **availabilityId** : This id paremeter is used to select the required data object that will be updated **dayOfWeek** : Day of week: sunday-saturday. **startTime** : Start time of window (HH:mm, 24h). **endTime** : End time of window (HH:mm, 24h). **isRecurring** : If true, this slot recurs weekly. **specificDate** : Specific date (YYYY-MM-DD) for non-recurring availability. Null for recurring slots. **teachingMode** : **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/availabilities/:availabilityId** ```js axios({ method: 'PATCH', url: `/v1/availabilities/${availabilityId}`, data: { dayOfWeek:"Enum", startTime:"String", endTime:"String", isRecurring:"Boolean", specificDate:"Date", teachingMode:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Availability` API **[Default delete API]** — This is the designated default `delete` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor deletes an availability record (only own, or admin). **Rest Route** The `deleteAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `deleteAvailability` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | **availabilityId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/availabilities/:availabilityId** ```js axios({ method: 'DELETE', url: `/v1/availabilities/${availabilityId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Availability` API **[Default get API]** — This is the designated default `get` API for the `availability` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one availability by id (tutor/owner or admin only). **Rest Route** The `getAvailability` API REST controller can be triggered via the following route: `/v1/availabilities/:availabilityId` **Rest Request Parameters** The `getAvailability` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | availabilityId | ID | true | request.params?.["availabilityId"] | **availabilityId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/availabilities/:availabilityId** ```js axios({ method: 'GET', url: `/v1/availabilities/${availabilityId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availability", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "availability": { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Availabilities` API **Rest Route** The `listAvailabilities` API REST controller can be triggered via the following route: `/v1/listavailabilities/:tutorProfileId` **Rest Request Parameters** The `listAvailabilities` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | true | request.params?.["tutorProfileId"] | **tutorProfileId** : FK to tutorCatalog:tutorProfile. Only owner tutor or admin can edit.. The parameter is used to query data. **Filter Parameters** The `listAvailabilities` api supports 1 optional filter parameter for filtering list results: **teachingMode** (`Enum`): Filter by teachingMode - Single: `?teachingMode=` (case-insensitive) - Multiple: `?teachingMode=&teachingMode=` - Null: `?teachingMode=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/listavailabilities/:tutorProfileId** ```js axios({ method: 'GET', url: `/v1/listavailabilities/${tutorProfileId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // teachingMode: '' // Filter by teachingMode } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "availabilities", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "availabilities": [ { "id": "ID", "tutorProfileId": "ID", "dayOfWeek": "Enum", "dayOfWeek_idx": "Integer", "startTime": "String", "endTime": "String", "isRecurring": "Boolean", "specificDate": "Date", "teachingMode": "Enum", "teachingMode_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Lessonslot` API **Rest Route** The `createLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots` **Rest Request Parameters** The `createLessonSlot` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | false | request.body?.["studentId"] | | scheduledDate | Date | true | request.body?.["scheduledDate"] | | scheduledTime | String | true | request.body?.["scheduledTime"] | | status | Enum | true | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | true | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | **coursePackId** : FK to tutorCatalog:coursePack. Only tutors for the pack, enrolled student, or admin may update/view. **studentId** : FK to auth:user (student). Set on booking. Nullable when open (free). **scheduledDate** : Date for the lesson slot (yyyy-mm-dd). **scheduledTime** : Start time of lesson (HH:mm 24h). **status** : State of lesson slot (free, booked, completed, canceled). **locationType** : **locationDetails** : Optional: Location address/details; editable after booking by either party. **sessionMode** : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. **meetLink** : Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/lessonslots** ```js axios({ method: 'POST', url: '/v1/lessonslots', data: { coursePackId:"ID", studentId:"ID", scheduledDate:"Date", scheduledTime:"String", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Lessonslot` API **[Default update API]** — This is the designated default `update` API for the `lessonSlot` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update lesson slot status/location. Tutor can edit any of their coursePack's slots; student can update their own booked slot location (if booked). Admin has override right. **Rest Route** The `updateLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `updateLessonSlot` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | | studentId | ID | false | request.body?.["studentId"] | | status | Enum | false | request.body?.["status"] | | locationType | Enum | false | request.body?.["locationType"] | | locationDetails | String | false | request.body?.["locationDetails"] | | sessionMode | Enum | false | request.body?.["sessionMode"] | | meetLink | String | false | request.body?.["meetLink"] | **lessonSlotId** : This id paremeter is used to select the required data object that will be updated **studentId** : FK to auth:user (student). Set on booking. Nullable when open (free). **status** : State of lesson slot (free, booked, completed, canceled). **locationType** : **locationDetails** : Optional: Location address/details; editable after booking by either party. **sessionMode** : Chosen delivery mode for this lesson. Set at booking time based on student choice or tutor's teachingMode. 'online' triggers Google Meet link generation, 'faceToFace' uses locationType/locationDetails. **meetLink** : Google Meet URL for online lessons. Auto-populated when sessionMode is 'online'. Null for face-to-face sessions. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'PATCH', url: `/v1/lessonslots/${lessonSlotId}`, data: { studentId:"ID", status:"Enum", locationType:"Enum", locationDetails:"String", sessionMode:"Enum", meetLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Lessonslot` API **[Default delete API]** — This is the designated default `delete` API for the `lessonSlot` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor can remove their own slot if free/booked. Admin can remove any. (Student may not delete). **Rest Route** The `deleteLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `deleteLessonSlot` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | **lessonSlotId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'DELETE', url: `/v1/lessonslots/${lessonSlotId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String", "sessionMode": "Enum", "sessionMode_idx": "Integer", "meetLink": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Lessonslot` API **Rest Route** The `getLessonSlot` API REST controller can be triggered via the following route: `/v1/lessonslots/:lessonSlotId` **Rest Request Parameters** The `getLessonSlot` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | lessonSlotId | ID | true | request.params?.["lessonSlotId"] | **lessonSlotId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/lessonslots/:lessonSlotId** ```js axios({ method: 'GET', url: `/v1/lessonslots/${lessonSlotId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlot", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "lessonSlot": { "isActive": true } } ``` ### `List Lessonslots` API **Rest Route** The `listLessonSlots` API REST controller can be triggered via the following route: `/v1/lessonslots` **Rest Request Parameters** The `listLessonSlots` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/lessonslots** ```js axios({ method: 'GET', url: '/v1/lessonslots', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "lessonSlots", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "lessonSlots": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Preliminarymeeting` API **[Default create API]** — This is the designated default `create` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student requests a screening meeting; only created if related coursePack requires screening. **Rest Route** The `createPreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings` **Rest Request Parameters** The `createPreliminaryMeeting` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | studentId | ID | true | request.body?.["studentId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | true | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | **coursePackId** : FK to tutorCatalog:coursePack (the advanced course) **studentId** : FK to auth:user (student who requested). **scheduledDatetime** : Datetime for screening meeting; may be null until both parties agree. **tutorDecision** : **comments** : Optional field for tutor to provide comments/notes about screening result. **meetingLink** : Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/preliminarymeetings** ```js axios({ method: 'POST', url: '/v1/preliminarymeetings', data: { coursePackId:"ID", studentId:"ID", scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "coursePack": {}, "tutorProfile": {}, "tutorUser": {}, "student": {} } ``` ### `Update Preliminarymeeting` API **[Default update API]** — This is the designated default `update` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor updates scheduled date/time, decision, or comments for screening meeting. Only tutor of coursePack or admin can approve/reject/set date; student can only propose initial. **Rest Route** The `updatePreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` **Rest Request Parameters** The `updatePreliminaryMeeting` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | | scheduledDatetime | Date | false | request.body?.["scheduledDatetime"] | | tutorDecision | Enum | false | request.body?.["tutorDecision"] | | comments | String | false | request.body?.["comments"] | | meetingLink | String | false | request.body?.["meetingLink"] | **preliminaryMeetingId** : This id paremeter is used to select the required data object that will be updated **scheduledDatetime** : Datetime for screening meeting; may be null until both parties agree. **tutorDecision** : **comments** : Optional field for tutor to provide comments/notes about screening result. **meetingLink** : Video call link (Google Meet, Zoom, etc.) for the screening interview. Set by the tutor when scheduling. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'PATCH', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { scheduledDatetime:"Date", tutorDecision:"Enum", comments:"String", meetingLink:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "student": {}, "coursePack": {} } ``` ### `Get Preliminarymeeting` API **[Default get API]** — This is the designated default `get` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single meeting by id: only tutor, student, or admin can access. **Rest Route** The `getPreliminaryMeeting` API REST controller can be triggered via the following route: `/v1/preliminarymeetings/:preliminaryMeetingId` **Rest Request Parameters** The `getPreliminaryMeeting` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | preliminaryMeetingId | ID | true | request.params?.["preliminaryMeetingId"] | **preliminaryMeetingId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/preliminarymeetings/:preliminaryMeetingId** ```js axios({ method: 'GET', url: `/v1/preliminarymeetings/${preliminaryMeetingId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeeting", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "preliminaryMeeting": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Preliminarymeetings` API **[Default list API]** — This is the designated default `list` API for the `preliminaryMeeting` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Tutor can list all meetings for their courses; students see their own; admin sees all. **Rest Route** The `listPreliminaryMeetings` API REST controller can be triggered via the following route: `/v1/preliminarymeetings` **Rest Request Parameters** The `listPreliminaryMeetings` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/preliminarymeetings** ```js axios({ method: 'GET', url: '/v1/preliminarymeetings', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "preliminaryMeetings", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "preliminaryMeetings": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "scheduledDatetime": "Date", "tutorDecision": "Enum", "tutorDecision_idx": "Integer", "comments": "String", "meetingLink": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## tutorhub-enrollmentmanagement-service **Version:** `1.0.76` Handles enrollments (course booking, lesson/slot allocation, fulfillment/pre-check, and payment via Stripe) and refund workflow (strictly after first lesson only, auto approved, and Stripe-based). Exposes all enrollment/payment/refund status for admins, tutors, and students. All business state transitions are auditable for analytics and compliance. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the EnrollmentManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our EnrollmentManagement Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the EnrollmentManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying EnrollmentManagement objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the EnrollmentManagement Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the EnrollmentManagement service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the EnrollmentManagement service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the EnrollmentManagement service. This service is configured to listen for HTTP requests on port `3003`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/enrollmentmanagement-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/enrollmentmanagement-api` * **Production:** `https://tutorhub.mindbricks.co/enrollmentmanagement-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the EnrollmentManagement service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `EnrollmentManagement` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `EnrollmentManagement` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `EnrollmentManagement` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources EnrollmentManagement service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### Enrollment resource *Resource Definition* : Represents a student's enrollment in a structured course pack: includes booking transaction, lesson slots, pricing, full payment processing, refund eligibility status, and traceable transitions. *Enrollment Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **coursePackId** | ID | | | *FK to purchased course pack.* | | **studentId** | ID | | | *FK to enrolling student (auth:user).* | | **tutorProfileId** | ID | | | *FK to the course's tutorProfile for admin/analytics.* | | **lessonSlotIds** | ID | | | *IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot).* | | **totalAmount** | Double | | | *Total amount paid for enrollment (for all slots/pack, pre-promotion/refund).* | | **currency** | String | | | *3-letter ISO currency code (e.g., 'USD', 'EUR').* | | **paymentStatus** | Enum | | | *Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation).* | | **refundStatus** | Enum | | | *Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow.* | | **enrollmentStatus** | Enum | | | *Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated).* | | **enrolledAt** | Date | | | *Datetime of completed enrollment (post-payment).* | | **paymentConfirmation** | Enum | | | *An automatic property that is used to check the confirmed status of the payment set by webhooks.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### paymentStatus Enum Property *Property Definition* : Status of payment for enrollment: pending, paid, refunded (mapped by Stripe automation).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **paid** | `"paid""` | 1 | | **refunded** | `"refunded""` | 2 | ##### refundStatus Enum Property *Property Definition* : Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **notRequested** | `"notRequested""` | 0 | | **eligible** | `"eligible""` | 1 | | **processed** | `"processed""` | 2 | | **ineligible** | `"ineligible""` | 3 | ##### enrollmentStatus Enum Property *Property Definition* : Enrollment status: pending (not paid), active (paid and in-progress), completed (all lessons done), canceled (user or system initiated).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **active** | `"active""` | 1 | | **completed** | `"completed""` | 2 | | **canceled** | `"canceled""` | 3 | ##### paymentConfirmation Enum Property *Property Definition* : An automatic property that is used to check the confirmed status of the payment set by webhooks.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **processing** | `"processing""` | 1 | | **paid** | `"paid""` | 2 | | **canceled** | `"canceled""` | 3 | ### RefundRequest resource *Resource Definition* : A request by a student (or in rare cases, admin) for a refund on a specific enrollment—limited to post-first lesson only, automatically approved and processed if eligible. *RefundRequest Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **enrollmentId** | ID | | | *FK to enrollment object for which refund is being requested (unique: one refund per enrollment).* | | **requestedBy** | ID | | | *User (student) making the refund request (auth:user id).* | | **requestedAt** | Date | | | *Datetime refund was requested.* | | **processedAt** | Date | | | *When refund was processed by system (auto-approval).* | | **status** | Enum | | | *Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly).* | | **reason** | String | | | *User-supplied reason for requesting refund.* | | **firstLessonCompleted** | Boolean | | | *True if this refund is after first lesson (enforced by workflow); must be checked before approval.* | | **adminNote** | String | | | *Admin note explaining the refund decision (approve/reject reason).* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### status Enum Property *Property Definition* : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | | **autoApproved** | `"autoApproved""` | 3 | ### Sys_enrollmentPayment resource *Resource Definition* : A payment storage object to store the payment life cyle of orders based on enrollment object. It is autocreated based on the source object's checkout config *Sys_enrollmentPayment Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **ownerId** | ID | | | * An ID value to represent owner user who created the order* | | **orderId** | ID | | | *an ID value to represent the orderId which is the ID parameter of the source enrollment object* | | **paymentId** | String | | | *A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type* | | **paymentStatus** | String | | | *A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.* | | **statusLiteral** | String | | | *A string value to represent the logical payment status which belongs to the application lifecycle itself.* | | **redirectUrl** | String | | | *A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.* | ### Sys_paymentCustomer resource *Resource Definition* : A payment storage object to store the customer values of the payment platform *Sys_paymentCustomer Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **userId** | ID | | | * An ID value to represent the user who is created as a stripe customer* | | **customerId** | String | | | *A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway* | | **platform** | String | | | *A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.* | ### Sys_paymentMethod resource *Resource Definition* : A payment storage object to store the payment methods of the platform customers *Sys_paymentMethod Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **paymentMethodId** | String | | | *A string value to represent the id of the payment method on the payment platform.* | | **userId** | ID | | | * An ID value to represent the user who owns the payment method* | | **customerId** | String | | | *A string value to represent the customer id which is generated on the payment gateway.* | | **cardHolderName** | String | | | *A string value to represent the name of the card holder. It can be different than the registered customer.* | | **cardHolderZip** | String | | | *A string value to represent the zip code of the card holder. It is used for address verification in specific countries.* | | **platform** | String | | | *A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.* | | **cardInfo** | Object | | | *A Json value to store the card details of the payment method.* | ## Business Api ### `Create Enrollment` API **[Default create API]** — This is the designated default `create` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Creates a new enrollment for a student in a selected course pack and selected lesson slots. Enforces booking prerequisites (availability, non-duplication, preliminary meeting if flagged in coursePack), and triggers Stripe payment. Updates all associated lesson slot statuses to booked. Enrollment remains pending until payment confirmed by Stripe webhook. **API Frontend Description By The Backend Architect** Student chooses course pack, selects lesson slots, triggers enrollment and Stripe payment. If the course requires preliminary screening, checks that it was passed before proceeding. If payment fails, booking is not confirmed. Successful booking sets lesson slots status to 'booked' and opens enrollment. Student, tutor, and admin can see details. **Rest Route** The `createEnrollment` API REST controller can be triggered via the following route: `/v1/enrollments` **Rest Request Parameters** The `createEnrollment` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | true | request.body?.["coursePackId"] | | tutorProfileId | ID | true | request.body?.["tutorProfileId"] | | lessonSlotIds | ID | true | request.body?.["lessonSlotIds"] | | totalAmount | Double | true | request.body?.["totalAmount"] | | currency | String | true | request.body?.["currency"] | | refundStatus | Enum | true | request.body?.["refundStatus"] | | enrolledAt | Date | false | request.body?.["enrolledAt"] | **coursePackId** : FK to purchased course pack. **tutorProfileId** : FK to the course's tutorProfile for admin/analytics. **lessonSlotIds** : IDs for reserved lesson slots with this enrollment (must exist in courseScheduling:lessonSlot). **totalAmount** : Total amount paid for enrollment (for all slots/pack, pre-promotion/refund). **currency** : 3-letter ISO currency code (e.g., 'USD', 'EUR'). **refundStatus** : Tracks refund state: notRequested, eligible, processed, ineligible. Managed by workflow. **enrolledAt** : Datetime of completed enrollment (post-payment). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/enrollments** ```js axios({ method: 'POST', url: '/v1/enrollments', data: { coursePackId:"ID", tutorProfileId:"ID", lessonSlotIds:"ID", totalAmount:"Double", currency:"String", refundStatus:"Enum", enrolledAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Enrollment` API **[Default get API]** — This is the designated default `get` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single enrollment, including all details and linked objects (student, coursePack, lessonSlots). Only the enrollment's student, tutor, or admin may view. **API Frontend Description By The Backend Architect** Enrollment owners (student), relevant tutor, and admin can see all details of an enrollment via this API. Contains lesson slot list, linked pack, payment/refund status, fulfillment states for transparency. **Rest Route** The `getEnrollment` API REST controller can be triggered via the following route: `/v1/enrollments/:enrollmentId` **Rest Request Parameters** The `getEnrollment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | **enrollmentId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/enrollments/:enrollmentId** ```js axios({ method: 'GET', url: `/v1/enrollments/${enrollmentId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "enrollment": { "coursePack": { "tutorProfileId": "ID", "title": "String", "price": "Double", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer" }, "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer", "locationType": "Enum", "locationType_idx": "Integer", "locationDetails": "String" }, {}, {} ], "student": { "fullname": "String", "avatar": "String" }, "tutorProfile": { "tutorId": "ID", "certifications": "String", "bio": "Text", "profilePhoto": "String" }, "isActive": true } } ``` ### `List Enrollments` API **[Default list API]** — This is the designated default `list` API for the `enrollment` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all enrollments. Admin sees all; students see their enrollments; tutors see enrollments where their tutorProfileId matches. **API Frontend Description By The Backend Architect** Admins see all enrollments; students see their own; tutors can filter enrollments to their packs by tutorProfileId. Response is enriched with embedded course, lesson, and user details as requested by the frontend. **Rest Route** The `listEnrollments` API REST controller can be triggered via the following route: `/v1/enrollments` **Rest Request Parameters** The `listEnrollments` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | false | request.query?.["tutorProfileId"] | **tutorProfileId** : Optional tutor profile ID filter for tutors to see enrollments in their courses. **Filter Parameters** The `listEnrollments` api supports 1 optional filter parameter for filtering list results: **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/enrollments** ```js axios({ method: 'GET', url: '/v1/enrollments', data: { }, params: { tutorProfileId:'"ID"', // Filter parameters (see Filter Parameters section above) // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "coursePack": [ { "title": "String", "category": "String", "schedulingType": "Enum", "schedulingType_idx": "Integer", "isActive": true }, {}, {} ], "lessonSlots": [ { "scheduledDate": "Date", "scheduledTime": "String", "status": "Enum", "status_idx": "Integer" }, {}, {} ], "student": [ { "email": "String", "fullname": "String", "avatar": "String" }, {}, {} ], "tutorProfile": [ { "tutorId": "ID", "bio": "Text" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Refundrequest` API **[Default create API]** — This is the designated default `create` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student files refund request for a completed enrollment only after first lesson and only if no additional lessons are complete. Auto-approves, updates enrollment statuses, and triggers Stripe refund if eligible. **API Frontend Description By The Backend Architect** Students can trigger a refund for their enrollment only after first lesson, provided no additional lessons have been completed. The refund is auto-approved and reflected in both user's and admin's views; tutor and admin are notified. No manual approval or asynchronous queue, strictly within narrow business criteria. **Rest Route** The `createRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests` **Rest Request Parameters** The `createRefundRequest` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.body?.["enrollmentId"] | | requestedAt | Date | true | request.body?.["requestedAt"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | true | request.body?.["status"] | | reason | String | true | request.body?.["reason"] | | firstLessonCompleted | Boolean | true | request.body?.["firstLessonCompleted"] | | adminNote | String | false | request.body?.["adminNote"] | **enrollmentId** : FK to enrollment object for which refund is being requested (unique: one refund per enrollment). **requestedAt** : Datetime refund was requested. **processedAt** : When refund was processed by system (auto-approval). **status** : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). **reason** : User-supplied reason for requesting refund. **firstLessonCompleted** : True if this refund is after first lesson (enforced by workflow); must be checked before approval. **adminNote** : Admin note explaining the refund decision (approve/reject reason). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/refundrequests** ```js axios({ method: 'POST', url: '/v1/refundrequests', data: { enrollmentId:"ID", requestedAt:"Date", processedAt:"Date", status:"Enum", reason:"String", firstLessonCompleted:"Boolean", adminNote:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Refundrequest` API **[Default get API]** — This is the designated default `get` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get refund request record for audit—visible to student (their own), tutor (if their course), or admin. Linked enrollment, user, and status are included. **API Frontend Description By The Backend Architect** Students check status of their refund request; tutors may audit if linked to their courses; admins can view all. Details include enrollment and state for auditing. **Rest Route** The `getRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests/:refundRequestId` **Rest Request Parameters** The `getRefundRequest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | **refundRequestId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/refundrequests/:refundRequestId** ```js axios({ method: 'GET', url: `/v1/refundrequests/${refundRequestId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "refundRequest": { "enrollment": { "coursePackId": "ID", "studentId": "ID" }, "isActive": true } } ``` ### `List Refundrequests` API **[Default list API]** — This is the designated default `list` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all refund requests (students see their own, admins see all, tutors see linked to their courses via coursePack). **API Frontend Description By The Backend Architect** Admins list all refund requests; students see their submitted refunds; tutors see those linked to their courses for reporting and audit. Each item shows enrollment link and high-level audit fields. **Rest Route** The `listRefundRequests` API REST controller can be triggered via the following route: `/v1/refundrequests` **Rest Request Parameters** The `listRefundRequests` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/refundrequests** ```js axios({ method: 'GET', url: '/v1/refundrequests', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequests", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "refundRequests": [ { "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "totalAmount": "Double", "currency": "String" }, {}, {} ], "coursePack": { "title": "String" }, "requester": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Refundrequest` API **[Default update API]** — This is the designated default `update` API for the `refundRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin updates a refund request: approve or reject with an admin note. Only admins can update refund requests. **API Frontend Description By The Backend Architect** Admin-only endpoint for processing pending refund requests. Admin sets status to approved or rejected and optionally provides an adminNote explaining the decision. processedAt is set automatically on approval/rejection. **Rest Route** The `updateRefundRequest` API REST controller can be triggered via the following route: `/v1/refundrequests/:refundRequestId` **Rest Request Parameters** The `updateRefundRequest` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | refundRequestId | ID | true | request.params?.["refundRequestId"] | | processedAt | Date | false | request.body?.["processedAt"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | **refundRequestId** : This id paremeter is used to select the required data object that will be updated **processedAt** : When refund was processed by system (auto-approval). **status** : Refund status: pending, approved, rejected, autoApproved (system processed/approved instantly). **adminNote** : Admin note explaining the refund decision (approve/reject reason). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refundrequests/:refundRequestId** ```js axios({ method: 'PATCH', url: `/v1/refundrequests/${refundRequestId}`, data: { processedAt:"Date", status:"Enum", adminNote:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Cancel Enrollment` API Admin force-cancels an enrollment. Sets enrollmentStatus to canceled, paymentStatus to refunded, refundStatus to processed. Used when a tutor is banned/suspended or a course is removed. **API Frontend Description By The Backend Architect** Admin-only action to force-cancel an enrollment. Used when tutor is banned, suspended, or course is removed. **Rest Route** The `cancelEnrollment` API REST controller can be triggered via the following route: `/v1/cancelenrollment/:enrollmentId` **Rest Request Parameters** The `cancelEnrollment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | cancelReason | String | | request.body?.["cancelReason"] | **enrollmentId** : This id paremeter is used to select the required data object that will be updated **cancelReason** : Admin reason for canceling the enrollment **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/cancelenrollment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/cancelenrollment/${enrollmentId}`, data: { cancelReason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Admin Refundenrollment` API Admin-initiated refund for an enrollment. Creates a refundRequest with autoApproved status, cancels the enrollment, and triggers Stripe refund. No student eligibility checks — admin override. **API Frontend Description By The Backend Architect** Admin-only action to refund an enrollment on behalf of a student. Used when tutor is banned/suspended, course removed, or admin decides a refund is warranted. The enrollment is immediately canceled and a refund request record is created for audit. **Rest Route** The `adminRefundEnrollment` API REST controller can be triggered via the following route: `/v1/adminrefundenrollment` **Rest Request Parameters** The `adminRefundEnrollment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | | reason | String | | request.body?.["reason"] | **enrollmentId** : The enrollment to refund **reason** : Admin reason for issuing the refund **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminrefundenrollment** ```js axios({ method: 'POST', url: '/v1/adminrefundenrollment', data: { enrollmentId:"ID", reason:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "refundRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "refundRequest": { "id": "ID", "enrollmentId": "ID", "requestedBy": "ID", "requestedAt": "Date", "processedAt": "Date", "status": "Enum", "status_idx": "Integer", "reason": "String", "firstLessonCompleted": "Boolean", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Cascade Tutorban` API Admin cascade: cancel all active enrollments for a banned/suspended tutor. **API Frontend Description By The Backend Architect** Called after admin bans or suspends a tutor. Cancels all active enrollments and frees slots. **Rest Route** The `cascadeTutorBan` API REST controller can be triggered via the following route: `/v1/cascadetutorban` **Rest Request Parameters** The `cascadeTutorBan` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | tutorProfileId | ID | | request.body?.["tutorProfileId"] | | reason | String | | request.body?.["reason"] | **tutorProfileId** : The tutor profile whose enrollments should be canceled **reason** : Reason for cascade cancellation **Filter Parameters** The `cascadeTutorBan` api supports 1 optional filter parameter for filtering list results: **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/cascadetutorban** ```js axios({ method: 'POST', url: '/v1/cascadetutorban', data: { tutorProfileId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section above) // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Cascade Courseremoval` API Admin cascade: cancel all active enrollments for a removed course pack. **API Frontend Description By The Backend Architect** Called after admin removes a course. Cancels all active enrollments and frees slots. **Rest Route** The `cascadeCourseRemoval` API REST controller can be triggered via the following route: `/v1/cascadecourseremoval` **Rest Request Parameters** The `cascadeCourseRemoval` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | coursePackId | ID | | request.body?.["coursePackId"] | | reason | String | | request.body?.["reason"] | **coursePackId** : The course pack whose enrollments should be canceled **reason** : Reason for cascade cancellation **Filter Parameters** The `cascadeCourseRemoval` api supports 1 optional filter parameter for filtering list results: **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/cascadecourseremoval** ```js axios({ method: 'POST', url: '/v1/cascadecourseremoval', data: { coursePackId:"ID", reason:"String", }, params: { // Filter parameters (see Filter Parameters section above) // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Cleanup Pendingenrollments` API Cleanup stale pending enrollments that were never paid. Cancels them and frees lesson slots. Default timeout: 60 minutes. **API Frontend Description By The Backend Architect** Admin or system cron calls this to clean up abandoned enrollments. Can also be triggered from frontend as a housekeeping action. **Rest Route** The `cleanupPendingEnrollments` API REST controller can be triggered via the following route: `/v1/cleanuppendingenrollments` **Rest Request Parameters** The `cleanupPendingEnrollments` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | maxAgeMinutes | Integer | | request.body?.["maxAgeMinutes"] | **maxAgeMinutes** : How old (in minutes) a pending enrollment must be to get cleaned up. Default: 60 **Filter Parameters** The `cleanupPendingEnrollments` api supports 1 optional filter parameter for filtering list results: **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/cleanuppendingenrollments** ```js axios({ method: 'POST', url: '/v1/cleanuppendingenrollments', data: { maxAgeMinutes:"Integer", }, params: { // Filter parameters (see Filter Parameters section above) // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Check Enrollmentcompletion` API Check if all lesson slots in an enrollment are completed and mark enrollment as completed if so. **API Frontend Description By The Backend Architect** Called after a lesson is marked completed. Checks if all lessons are done and auto-completes the enrollment. **Rest Route** The `checkEnrollmentCompletion` API REST controller can be triggered via the following route: `/v1/checkenrollmentcompletion` **Rest Request Parameters** The `checkEnrollmentCompletion` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | | request.body?.["enrollmentId"] | **enrollmentId** : The enrollment to check for completion **Filter Parameters** The `checkEnrollmentCompletion` api supports 1 optional filter parameter for filtering list results: **paymentConfirmation** (`Enum`): An automatic property that is used to check the confirmed status of the payment set by webhooks. - Single: `?paymentConfirmation=` (case-insensitive) - Multiple: `?paymentConfirmation=&paymentConfirmation=` - Null: `?paymentConfirmation=null` **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/checkenrollmentcompletion** ```js axios({ method: 'POST', url: '/v1/checkenrollmentcompletion', data: { enrollmentId:"ID", }, params: { // Filter parameters (see Filter Parameters section above) // paymentConfirmation: '' // Filter by paymentConfirmation } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollments", "method": "POST", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "enrollments": [ { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Enrollmentpayment` API This route is used to get the payment information by ID. **Rest Route** The `getEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `getEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | **sys_enrollmentPaymentId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Enrollmentpayments` API This route is used to list all payments. **Rest Route** The `listEnrollmentPayments` API REST controller can be triggered via the following route: `/v1/enrollmentpayments` **Rest Request Parameters** **Filter Parameters** The `listEnrollmentPayments` api supports 6 optional filter parameters for filtering list results: **ownerId** (`ID`): An ID value to represent owner user who created the order - Single: `?ownerId=` - Multiple: `?ownerId=&ownerId=` - Null: `?ownerId=null` **orderId** (`ID`): an ID value to represent the orderId which is the ID parameter of the source enrollment object - Single: `?orderId=` - Multiple: `?orderId=&orderId=` - Null: `?orderId=null` **paymentId** (`String`): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type - Single (partial match, case-insensitive): `?paymentId=` - Multiple: `?paymentId=&paymentId=` - Null: `?paymentId=null` **paymentStatus** (`String`): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. - Single (partial match, case-insensitive): `?paymentStatus=` - Multiple: `?paymentStatus=&paymentStatus=` - Null: `?paymentStatus=null` **statusLiteral** (`String`): A string value to represent the logical payment status which belongs to the application lifecycle itself. - Single (partial match, case-insensitive): `?statusLiteral=` - Multiple: `?statusLiteral=&statusLiteral=` - Null: `?statusLiteral=null` **redirectUrl** (`String`): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. - Single (partial match, case-insensitive): `?redirectUrl=` - Multiple: `?redirectUrl=&redirectUrl=` - Null: `?redirectUrl=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/enrollmentpayments** ```js axios({ method: 'GET', url: '/v1/enrollmentpayments', data: { }, params: { // Filter parameters (see Filter Parameters section above) // ownerId: '' // Filter by ownerId // orderId: '' // Filter by orderId // paymentId: '' // Filter by paymentId // paymentStatus: '' // Filter by paymentStatus // statusLiteral: '' // Filter by statusLiteral // redirectUrl: '' // Filter by redirectUrl } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayments", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_enrollmentPayments": [ { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Enrollmentpayment` API This route is used to create a new payment. **Rest Route** The `createEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment` **Rest Request Parameters** The `createEnrollmentPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.body?.["orderId"] | | paymentId | String | true | request.body?.["paymentId"] | | paymentStatus | String | true | request.body?.["paymentStatus"] | | statusLiteral | String | true | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source enrollment object **paymentId** : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type **paymentStatus** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/enrollmentpayment** ```js axios({ method: 'POST', url: '/v1/enrollmentpayment', data: { orderId:"ID", paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayment", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Enrollmentpayment` API This route is used to update an existing payment. **Rest Route** The `updateEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `updateEnrollmentPayment` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | | paymentId | String | false | request.body?.["paymentId"] | | paymentStatus | String | false | request.body?.["paymentStatus"] | | statusLiteral | String | false | request.body?.["statusLiteral"] | | redirectUrl | String | false | request.body?.["redirectUrl"] | **sys_enrollmentPaymentId** : This id paremeter is used to select the required data object that will be updated **paymentId** : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type **paymentStatus** : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. **statusLiteral** : A string value to represent the logical payment status which belongs to the application lifecycle itself. **redirectUrl** : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'PATCH', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, data: { paymentId:"String", paymentStatus:"String", statusLiteral:"String", redirectUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Enrollmentpayment` API This route is used to delete a payment. **Rest Route** The `deleteEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/enrollmentpayment/:sys_enrollmentPaymentId` **Rest Request Parameters** The `deleteEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_enrollmentPaymentId | ID | true | request.params?.["sys_enrollmentPaymentId"] | **sys_enrollmentPaymentId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/enrollmentpayment/:sys_enrollmentPaymentId** ```js axios({ method: 'DELETE', url: `/v1/enrollmentpayment/${sys_enrollmentPaymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayment", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Enrollmentpaymentbyorderid` API This route is used to get the payment information by order id. **Rest Route** The `getEnrollmentPaymentByOrderId` API REST controller can be triggered via the following route: `/v1/enrollmentpaymentbyorderid/:orderId` **Rest Request Parameters** The `getEnrollmentPaymentByOrderId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | orderId | ID | true | request.params?.["orderId"] | **orderId** : an ID value to represent the orderId which is the ID parameter of the source enrollment object. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/enrollmentpaymentbyorderid/:orderId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbyorderid/${orderId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Enrollmentpaymentbypaymentid` API This route is used to get the payment information by payment id. **Rest Route** The `getEnrollmentPaymentByPaymentId` API REST controller can be triggered via the following route: `/v1/enrollmentpaymentbypaymentid/:paymentId` **Rest Request Parameters** The `getEnrollmentPaymentByPaymentId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | paymentId | String | true | request.params?.["paymentId"] | **paymentId** : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/enrollmentpaymentbypaymentid/:paymentId** ```js axios({ method: 'GET', url: `/v1/enrollmentpaymentbypaymentid/${paymentId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_enrollmentPayment", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_enrollmentPayment": { "id": "ID", "ownerId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "String", "statusLiteral": "String", "redirectUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Start Enrollmentpayment` API Start payment for enrollment **Rest Route** The `startEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/startenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `startEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | true | request.body?.["paymentUserParams"] | **enrollmentId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/startenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/startenrollmentpayment/${enrollmentId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Refresh Enrollmentpayment` API Refresh payment info for enrollment from Stripe **Rest Route** The `refreshEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/refreshenrollmentpayment/:enrollmentId` **Rest Request Parameters** The `refreshEnrollmentPayment` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | true | request.params?.["enrollmentId"] | | paymentUserParams | Object | false | request.body?.["paymentUserParams"] | **enrollmentId** : This id paremeter is used to select the required data object that will be updated **paymentUserParams** : The user parameters that should be defined to refresh a stripe payment process **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/refreshenrollmentpayment/:enrollmentId** ```js axios({ method: 'PATCH', url: `/v1/refreshenrollmentpayment/${enrollmentId}`, data: { paymentUserParams:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Callback Enrollmentpayment` API Refresh payment values by gateway webhook call for enrollment **Rest Route** The `callbackEnrollmentPayment` API REST controller can be triggered via the following route: `/v1/callbackenrollmentpayment` **Rest Request Parameters** The `callbackEnrollmentPayment` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | enrollmentId | ID | false | request.body?.["enrollmentId"] | **enrollmentId** : The order id parameter that will be read from webhook callback params **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/callbackenrollmentpayment** ```js axios({ method: 'POST', url: '/v1/callbackenrollmentpayment', data: { enrollmentId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "enrollment", "method": "POST", "action": "update", "appVersion": "Version", "rowCount": 1, "enrollment": { "id": "ID", "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID", "lessonSlotIds": "ID", "totalAmount": "Double", "currency": "String", "paymentStatus": "Enum", "paymentStatus_idx": "Integer", "refundStatus": "Enum", "refundStatus_idx": "Integer", "enrollmentStatus": "Enum", "enrollmentStatus_idx": "Integer", "enrolledAt": "Date", "paymentConfirmation": "Enum", "paymentConfirmation_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "paymentResult": { "paymentTicketId": "ID", "orderId": "ID", "paymentId": "String", "paymentStatus": "Enum", "paymentIntentInfo": "Object", "statusLiteral": "String", "amount": "Double", "currency": "String", "success": true, "description": "String", "metadata": "Object", "paymentUserParams": "Object" } } ``` ### `Get Paymentcustomerbyuserid` API This route is used to get the payment customer information by user id. **Rest Route** The `getPaymentCustomerByUserId` API REST controller can be triggered via the following route: `/v1/paymentcustomers/:userId` **Rest Request Parameters** The `getPaymentCustomerByUserId` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomers/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomer", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_paymentCustomer": { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Paymentcustomers` API This route is used to list all payment customers. **Rest Route** The `listPaymentCustomers` API REST controller can be triggered via the following route: `/v1/paymentcustomers` **Rest Request Parameters** **Filter Parameters** The `listPaymentCustomers` api supports 3 optional filter parameters for filtering list results: **userId** (`ID`): An ID value to represent the user who is created as a stripe customer - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **customerId** (`String`): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **platform** (`String`): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomers** ```js axios({ method: 'GET', url: '/v1/paymentcustomers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // userId: '' // Filter by userId // customerId: '' // Filter by customerId // platform: '' // Filter by platform } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentCustomers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentCustomers": [ { "id": "ID", "userId": "ID", "customerId": "String", "platform": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Paymentcustomermethods` API This route is used to list all payment customer methods. **Rest Route** The `listPaymentCustomerMethods` API REST controller can be triggered via the following route: `/v1/paymentcustomermethods/:userId` **Rest Request Parameters** The `listPaymentCustomerMethods` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : An ID value to represent the user who owns the payment method. The parameter is used to query data. **Filter Parameters** The `listPaymentCustomerMethods` api supports 6 optional filter parameters for filtering list results: **paymentMethodId** (`String`): A string value to represent the id of the payment method on the payment platform. - Single (partial match, case-insensitive): `?paymentMethodId=` - Multiple: `?paymentMethodId=&paymentMethodId=` - Null: `?paymentMethodId=null` **customerId** (`String`): A string value to represent the customer id which is generated on the payment gateway. - Single (partial match, case-insensitive): `?customerId=` - Multiple: `?customerId=&customerId=` - Null: `?customerId=null` **cardHolderName** (`String`): A string value to represent the name of the card holder. It can be different than the registered customer. - Single (partial match, case-insensitive): `?cardHolderName=` - Multiple: `?cardHolderName=&cardHolderName=` - Null: `?cardHolderName=null` **cardHolderZip** (`String`): A string value to represent the zip code of the card holder. It is used for address verification in specific countries. - Single (partial match, case-insensitive): `?cardHolderZip=` - Multiple: `?cardHolderZip=&cardHolderZip=` - Null: `?cardHolderZip=null` **platform** (`String`): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future. - Single (partial match, case-insensitive): `?platform=` - Multiple: `?platform=&platform=` - Null: `?platform=null` **cardInfo** (`Object`): A Json value to store the card details of the payment method. - Single: `?cardInfo=` - Multiple: `?cardInfo=&cardInfo=` - Null: `?cardInfo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/paymentcustomermethods/:userId** ```js axios({ method: 'GET', url: `/v1/paymentcustomermethods/${userId}`, data: { }, params: { // Filter parameters (see Filter Parameters section above) // paymentMethodId: '' // Filter by paymentMethodId // customerId: '' // Filter by customerId // cardHolderName: '' // Filter by cardHolderName // cardHolderZip: '' // Filter by cardHolderZip // platform: '' // Filter by platform // cardInfo: '' // Filter by cardInfo } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_paymentMethods", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_paymentMethods": [ { "id": "ID", "paymentMethodId": "String", "userId": "ID", "customerId": "String", "cardHolderName": "String", "cardHolderZip": "String", "platform": "String", "cardInfo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## tutorhub-platformadmin-service **Version:** `1.0.2` ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the PlatformAdmin Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our PlatformAdmin Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the PlatformAdmin Service via HTTP requests for purposes such as creating, updating, deleting and querying PlatformAdmin objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the PlatformAdmin Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the PlatformAdmin service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the PlatformAdmin service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the PlatformAdmin service. This service is configured to listen for HTTP requests on port `3005`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/platformadmin-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/platformadmin-api` * **Production:** `https://tutorhub.mindbricks.co/platformadmin-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the PlatformAdmin service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `PlatformAdmin` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `PlatformAdmin` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `PlatformAdmin` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources PlatformAdmin service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### AdminIssue resource *AdminIssue Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **reportedBy** | ID | | | *User who filed the issue (student or tutor).* | | **reportedUserId** | ID | | | *(Optional) User being complained about* | | **coursePackId** | ID | | | *(Optional) ID of the related coursePack, if content/pack is complained about* | | **description** | Text | | | *Long text/body of the complaint/issue.* | | **issueType** | Enum | | | *Type of complaint (user, content, or other).* | | **status** | Enum | | | *Issue investigation status (open/investigating/resolved/dismissed).* | | **adminNote** | String | | | *Internal/admin note for progress or findings (not visible to original user).* | | **resolution** | Enum | | | *Resolution outcome chosen by admin when closing the issue.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### issueType Enum Property *Property Definition* : Type of complaint (user, content, or other).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **user** | `"user""` | 0 | | **content** | `"content""` | 1 | | **other** | `"other""` | 2 | ##### status Enum Property *Property Definition* : Issue investigation status (open/investigating/resolved/dismissed).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **open** | `"open""` | 0 | | **investigating** | `"investigating""` | 1 | | **resolved** | `"resolved""` | 2 | | **dismissed** | `"dismissed""` | 3 | ##### resolution Enum Property *Property Definition* : Resolution outcome chosen by admin when closing the issue.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **dismissed** | `"dismissed""` | 0 | | **warned** | `"warned""` | 1 | | **courseEditRequired** | `"courseEditRequired""` | 2 | | **courseRemoved** | `"courseRemoved""` | 3 | | **userSuspended** | `"userSuspended""` | 4 | | **userBanned** | `"userBanned""` | 5 | | **acknowledged** | `"acknowledged""` | 6 | ### AdminModerationAction resource *Resource Definition* : Action performed by an admin to moderate user, coursePack, profile, or material. All admin actions logged for audit trail. Only admins can create. *AdminModerationAction Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **adminId** | ID | | | *Admin performing moderation action.* | | **targetType** | Enum | | | *Moderation target type (user/coursePack/profile/material).* | | **targetId** | ID | | | *ID of moderation target object (userId, coursePackId, etc).* | | **actionType** | Enum | | | *Type of moderation action (suspend, ban, edit, remove, approve, warn).* | | **actionReason** | String | | | *Reason for moderation action, as recorded by the admin.* | | **actionDate** | Date | | | *Datetime when the action took place.* | | **targetUserId** | ID | | | *UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### targetType Enum Property *Property Definition* : Moderation target type (user/coursePack/profile/material).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **user** | `"user""` | 0 | | **coursePack** | `"coursePack""` | 1 | | **profile** | `"profile""` | 2 | | **material** | `"material""` | 3 | ##### actionType Enum Property *Property Definition* : Type of moderation action (suspend, ban, edit, remove, approve, warn).*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **suspend** | `"suspend""` | 0 | | **ban** | `"ban""` | 1 | | **edit** | `"edit""` | 2 | | **remove** | `"remove""` | 3 | | **approve** | `"approve""` | 4 | | **warn** | `"warn""` | 5 | ### AdminAnalyticsReport resource *Resource Definition* : Stores generated analytics/reporting URLs/metadata for admin dashboard access. Reports are generated by backend tasks/edge (future), but listing is for download/view. *AdminAnalyticsReport Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **reportType** | String | | | *Type of the analytics report (enrollments, revenue, complaints, etc).* | | **filterParams** | String | | | *Filter params as stringified JSON for reporting input.* | | **generatedAt** | Date | | | *Date/time report was generated.* | | **reportUrl** | String | | | *Accessible URL where generated report is stored (PDF, CSV, etc).* | ## Business Api ### `Create Adminissue` API **[Default create API]** — This is the designated default `create` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Student or tutor files a new complaint/issue. Admin receives for review/investigation. Only admins can update or alter status; creator can get their own. **Rest Route** The `createAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues` **Rest Request Parameters** The `createAdminIssue` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportedBy | ID | true | request.body?.["reportedBy"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | true | request.body?.["description"] | | issueType | Enum | true | request.body?.["issueType"] | | status | Enum | true | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | **reportedBy** : User who filed the issue (student or tutor). **reportedUserId** : (Optional) User being complained about **coursePackId** : (Optional) ID of the related coursePack, if content/pack is complained about **description** : Long text/body of the complaint/issue. **issueType** : Type of complaint (user, content, or other). **status** : Issue investigation status (open/investigating/resolved/dismissed). **adminNote** : Internal/admin note for progress or findings (not visible to original user). **resolution** : Resolution outcome chosen by admin when closing the issue. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminissues** ```js axios({ method: 'POST', url: '/v1/adminissues', data: { reportedBy:"ID", reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Adminissue` API **[Default update API]** — This is the designated default `update` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin investigates/updates an issue: change status, add internal note, resolve/dismiss. Strictly admin-only. **Rest Route** The `updateAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues/:adminIssueId` **Rest Request Parameters** The `updateAdminIssue` api has got 8 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | | reportedUserId | ID | false | request.body?.["reportedUserId"] | | coursePackId | ID | false | request.body?.["coursePackId"] | | description | Text | false | request.body?.["description"] | | issueType | Enum | false | request.body?.["issueType"] | | status | Enum | false | request.body?.["status"] | | adminNote | String | false | request.body?.["adminNote"] | | resolution | Enum | false | request.body?.["resolution"] | **adminIssueId** : This id paremeter is used to select the required data object that will be updated **reportedUserId** : (Optional) User being complained about **coursePackId** : (Optional) ID of the related coursePack, if content/pack is complained about **description** : Long text/body of the complaint/issue. **issueType** : Type of complaint (user, content, or other). **status** : Issue investigation status (open/investigating/resolved/dismissed). **adminNote** : Internal/admin note for progress or findings (not visible to original user). **resolution** : Resolution outcome chosen by admin when closing the issue. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/adminissues/:adminIssueId** ```js axios({ method: 'PATCH', url: `/v1/adminissues/${adminIssueId}`, data: { reportedUserId:"ID", coursePackId:"ID", description:"Text", issueType:"Enum", status:"Enum", adminNote:"String", resolution:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "adminIssue": { "id": "ID", "reportedBy": "ID", "reportedUserId": "ID", "coursePackId": "ID", "description": "Text", "issueType": "Enum", "issueType_idx": "Integer", "status": "Enum", "status_idx": "Integer", "adminNote": "String", "resolution": "Enum", "resolution_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "reporterUser": {} } ``` ### `Get Adminissue` API **[Default get API]** — This is the designated default `get` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetches a single issue by ID. Admins may get any; creator may get/view their own for status updates. **Rest Route** The `getAdminIssue` API REST controller can be triggered via the following route: `/v1/adminissues/:adminIssueId` **Rest Request Parameters** The `getAdminIssue` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminIssueId | ID | true | request.params?.["adminIssueId"] | **adminIssueId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminissues/:adminIssueId** ```js axios({ method: 'GET', url: `/v1/adminissues/${adminIssueId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssue", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminIssue": { "reporter": { "email": "String", "fullname": "String" }, "reportedUser": { "email": "String", "fullname": "String" }, "coursePack": { "tutorProfileId": "ID", "title": "String" }, "isActive": true } } ``` ### `List Adminissues` API **[Default list API]** — This is the designated default `list` API for the `adminIssue` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List issues with filters for admin dashboard: by status/type/target. Admin only. **Rest Route** The `listAdminIssues` API REST controller can be triggered via the following route: `/v1/adminissues` **Rest Request Parameters** The `listAdminIssues` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminissues** ```js axios({ method: 'GET', url: '/v1/adminissues', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reporter": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "reportedUser": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "coursePack": [ { "tutorProfileId": "ID", "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Adminmoderationaction` API **[Default create API]** — This is the designated default `create` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin records a moderation action against a user/object. Admin only. Write-side audit log for all moderator events. **Rest Route** The `createAdminModerationAction` API REST controller can be triggered via the following route: `/v1/adminmoderationactions` **Rest Request Parameters** The `createAdminModerationAction` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminId | ID | true | request.body?.["adminId"] | | targetType | Enum | true | request.body?.["targetType"] | | targetId | ID | true | request.body?.["targetId"] | | actionType | Enum | true | request.body?.["actionType"] | | actionReason | String | true | request.body?.["actionReason"] | | actionDate | Date | true | request.body?.["actionDate"] | | targetUserId | ID | true | request.body?.["targetUserId"] | **adminId** : Admin performing moderation action. **targetType** : Moderation target type (user/coursePack/profile/material). **targetId** : ID of moderation target object (userId, coursePackId, etc). **actionType** : Type of moderation action (suspend, ban, edit, remove, approve, warn). **actionReason** : Reason for moderation action, as recorded by the admin. **actionDate** : Datetime when the action took place. **targetUserId** : UserId of the person affected by the moderation action. For user moderation: the user being moderated. For content moderation: the tutor who owns the content. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminmoderationactions** ```js axios({ method: 'POST', url: '/v1/adminmoderationactions', data: { adminId:"ID", targetType:"Enum", targetId:"ID", actionType:"Enum", actionReason:"String", actionDate:"Date", targetUserId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminModerationAction", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "id": "ID", "adminId": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "actionType": "Enum", "actionType_idx": "Integer", "actionReason": "String", "actionDate": "Date", "targetUserId": "ID", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "targetUser": {} } ``` ### `Get Adminmoderationaction` API **[Default get API]** — This is the designated default `get` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one moderation action. Admin only. **Rest Route** The `getAdminModerationAction` API REST controller can be triggered via the following route: `/v1/adminmoderationactions/:adminModerationActionId` **Rest Request Parameters** The `getAdminModerationAction` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminModerationActionId | ID | true | request.params?.["adminModerationActionId"] | **adminModerationActionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminmoderationactions/:adminModerationActionId** ```js axios({ method: 'GET', url: `/v1/adminmoderationactions/${adminModerationActionId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminModerationAction", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminModerationAction": { "admin": { "email": "String", "fullname": "String" }, "isActive": true } } ``` ### `List Adminmoderationactions` API **[Default list API]** — This is the designated default `list` API for the `adminModerationAction` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all admin moderation actions, filterable by actionType/targetType/date. For admin dashboard audit log. **Rest Route** The `listAdminModerationActions` API REST controller can be triggered via the following route: `/v1/adminmoderationactions` **Rest Request Parameters** The `listAdminModerationActions` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminmoderationactions** ```js axios({ method: 'GET', url: '/v1/adminmoderationactions', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminModerationActions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminModerationActions": [ { "admin": [ { "email": "String", "fullname": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Adminanalyticsreport` API **[Default create API]** — This is the designated default `create` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create record for a new analytics report (usually admin-triggered on dashboard, actual report process may be async via edge controller in future). Admin-only; records metadata and download URL of available report. **Rest Route** The `createAdminAnalyticsReport` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports` **Rest Request Parameters** The `createAdminAnalyticsReport` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportType | String | true | request.body?.["reportType"] | | filterParams | String | false | request.body?.["filterParams"] | | generatedAt | Date | true | request.body?.["generatedAt"] | | reportUrl | String | true | request.body?.["reportUrl"] | **reportType** : Type of the analytics report (enrollments, revenue, complaints, etc). **filterParams** : Filter params as stringified JSON for reporting input. **generatedAt** : Date/time report was generated. **reportUrl** : Accessible URL where generated report is stored (PDF, CSV, etc). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/adminanalyticsreports** ```js axios({ method: 'POST', url: '/v1/adminanalyticsreports', data: { reportType:"String", filterParams:"String", generatedAt:"Date", reportUrl:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminAnalyticsReport", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "id": "ID", "reportType": "String", "filterParams": "String", "generatedAt": "Date", "reportUrl": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Adminanalyticsreport` API **[Default get API]** — This is the designated default `get` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get one analytics report record for download from admin dashboard. Admin only. **Rest Route** The `getAdminAnalyticsReport` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports/:adminAnalyticsReportId` **Rest Request Parameters** The `getAdminAnalyticsReport` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | adminAnalyticsReportId | ID | true | request.params?.["adminAnalyticsReportId"] | **adminAnalyticsReportId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminanalyticsreports/:adminAnalyticsReportId** ```js axios({ method: 'GET', url: `/v1/adminanalyticsreports/${adminAnalyticsReportId}`, data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminAnalyticsReport", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "adminAnalyticsReport": { "isActive": true } } ``` ### `List Adminanalyticsreports` API **[Default list API]** — This is the designated default `list` API for the `adminAnalyticsReport` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all analytics reports for admin dashboard access (download/view). Admin only. **Rest Route** The `listAdminAnalyticsReports` API REST controller can be triggered via the following route: `/v1/adminanalyticsreports` **Rest Request Parameters** The `listAdminAnalyticsReports` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/adminanalyticsreports** ```js axios({ method: 'GET', url: '/v1/adminanalyticsreports', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminAnalyticsReports", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminAnalyticsReports": [ { "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `List Myissues` API Students and tutors list their own reported issues. Ownership check ensures users only see their own reports. **Rest Route** The `listMyIssues` API REST controller can be triggered via the following route: `/v1/myissues` **Rest Request Parameters** The `listMyIssues` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myissues** ```js axios({ method: 'GET', url: '/v1/myissues', data: { }, params: { } }); ``` **REST Response** This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource. ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "adminIssues", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "adminIssues": [ { "reportedUser": [ { "email": "String", "fullname": "String" }, {}, {} ], "coursePack": [ { "title": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## tutorhub-messaging-service **Version:** `1.0.15` Real-time messaging service: student-tutor chat (bidirectional), admin-student warnings (one-way), admin-tutor communication (bidirectional). Uses RealtimeHub for WebSocket chat with persistence, typing, and read receipts. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Messaging Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Messaging Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the Messaging Service via HTTP requests for purposes such as creating, updating, deleting and querying Messaging objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the Messaging Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the Messaging service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the Messaging service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Messaging service. This service is configured to listen for HTTP requests on port `3000`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/messaging-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/messaging-api` * **Production:** `https://tutorhub.mindbricks.co/messaging-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the Messaging service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `Messaging` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Messaging` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `Messaging` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources Messaging service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### Conversation resource *Resource Definition* : Represents a chat channel between two participants. Types: studentTutor (bidirectional enrolled chat), adminStudent (one-way admin warnings), adminTutor (bidirectional admin-tutor communication). *Conversation Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **conversationType** | String | | | *Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions.* | | **participantA** | ID | | | *First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin.* | | **participantB** | ID | | | *Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor.* | | **enrollmentId** | ID | | | *FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context.* | | **lastMessageAt** | Date | | | *Timestamp of the most recent message. Used for sorting conversations in inbox.* | | **lastMessagePreview** | String | | | *Truncated preview of last message content. Shown in conversation list.* | | **status** | String | | | *Conversation status: active or closed.* | | **participantAName** | String | | | *Cached display name of participant A for quick rendering in conversation list.* | | **participantBName** | String | | | *Cached display name of participant B for quick rendering in conversation list.* | | **courseTitle** | String | | | *Cached course pack title for display. Set on conversation creation for studentTutor type.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### conversationType Enum Property *Property Definition* : Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **studentTutor** | `"studentTutor""` | 0 | | **adminStudent** | `"adminStudent""` | 1 | | **adminTutor** | `"adminTutor""` | 2 | ##### status Enum Property *Property Definition* : Conversation status: active or closed.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **active** | `"active""` | 0 | | **closed** | `"closed""` | 1 | ### ChatMessage resource *Resource Definition* : Auto-generated message DataObject for the chat RealtimeHub. Stores all messages with typed content payloads. *ChatMessage Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **roomId** | ID | | | *Reference to the room this message belongs to* | | **senderId** | ID | | | *Reference to the user who sent this message* | | **senderName** | String | | | *Display name of the sender (denormalized from user profile at send time)* | | **senderAvatar** | String | | | *Avatar URL of the sender (denormalized from user profile at send time)* | | **messageType** | Enum | | | *Content type discriminator for this message* | | **content** | Object | | | *Type-specific content payload (structure depends on messageType)* | | **timestamp** | | | | *Message creation time* | | **status** | Enum | | | *Message moderation status* | | **replyTo** | Object | | | *Reply thread reference { id, preview }* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### messageType Enum Property *Property Definition* : Content type discriminator for this message*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **text** | `"text""` | 0 | | **image** | `"image""` | 1 | | **document** | `"document""` | 2 | | **system** | `"system""` | 3 | | **warning** | `"warning""` | 4 | ##### status Enum Property *Property Definition* : Message moderation status*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **pending** | `"pending""` | 0 | | **approved** | `"approved""` | 1 | | **rejected** | `"rejected""` | 2 | ### ChatModeration resource *Resource Definition* : Auto-generated moderation DataObject for the chat RealtimeHub. Stores block and silence actions for room-level user moderation. *ChatModeration Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **roomId** | ID | | | *Reference to the room where the moderation action applies* | | **userId** | ID | | | *The user who is blocked or silenced* | | **action** | Enum | | | *Moderation action type* | | **reason** | Text | | | *Optional reason for the moderation action* | | **duration** | Integer | | | *Duration in seconds. 0 means permanent* | | **expiresAt** | | | | *Expiry timestamp. Null means permanent* | | **issuedBy** | ID | | | *The moderator who issued the action* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### action Enum Property *Property Definition* : Moderation action type*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **blocked** | `"blocked""` | 0 | | **silenced** | `"silenced""` | 1 | ## Business Api ### `Create Conversation` API **[Default create API]** — This is the designated default `create` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Creates a new conversation between two participants. For studentTutor type, requires valid enrollment. For adminStudent/adminTutor, only admin can create. **API Frontend Description By The Backend Architect** ## Create Conversation - Tutors/students can create studentTutor conversations. - Only admin can create adminStudent or adminTutor conversations. - Before creating, check if conversation already exists between the two participants of same type. **Rest Route** The `createConversation` API REST controller can be triggered via the following route: `/v1/conversations` **Rest Request Parameters** The `createConversation` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationType | String | true | request.body?.["conversationType"] | | participantA | ID | true | request.body?.["participantA"] | | participantB | ID | true | request.body?.["participantB"] | | enrollmentId | ID | false | request.body?.["enrollmentId"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | | lastMessagePreview | String | false | request.body?.["lastMessagePreview"] | | participantAName | String | false | request.body?.["participantAName"] | | participantBName | String | false | request.body?.["participantBName"] | | courseTitle | String | false | request.body?.["courseTitle"] | **conversationType** : Channel type: studentTutor, adminStudent, or adminTutor. Determines messaging permissions. **participantA** : First participant userId. For studentTutor: the student. For adminStudent/adminTutor: the admin. **participantB** : Second participant userId. For studentTutor: the tutor. For adminStudent: the student. For adminTutor: the tutor. **enrollmentId** : FK to enrollment. Only set for studentTutor conversations to link chat to enrollment context. **lastMessageAt** : Timestamp of the most recent message. Used for sorting conversations in inbox. **lastMessagePreview** : Truncated preview of last message content. Shown in conversation list. **participantAName** : Cached display name of participant A for quick rendering in conversation list. **participantBName** : Cached display name of participant B for quick rendering in conversation list. **courseTitle** : Cached course pack title for display. Set on conversation creation for studentTutor type. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/conversations** ```js axios({ method: 'POST', url: '/v1/conversations', data: { conversationType:"String", participantA:"ID", participantB:"ID", enrollmentId:"ID", lastMessageAt:"Date", lastMessagePreview:"String", participantAName:"String", participantBName:"String", courseTitle:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Conversation` API **[Default get API]** — This is the designated default `get` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single conversation by ID. Only participants or admin can view. **Rest Route** The `getConversation` API REST controller can be triggered via the following route: `/v1/conversations/:conversationId` **Rest Request Parameters** The `getConversation` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | conversationId | ID | true | request.params?.["conversationId"] | **conversationId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/conversations/:conversationId** ```js axios({ method: 'GET', url: `/v1/conversations/${conversationId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" } } } ``` ### `List Myconversations` API **[Default list API]** — This is the designated default `list` API for the `conversation` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Lists all conversations where the current user is a participant. Sorted by lastMessageAt descending. **API Frontend Description By The Backend Architect** ## Inbox / Conversation List - Shows all conversations for the logged-in user sorted by most recent. - Show: other participant name, last message preview, timestamp, unread badge. - For adminStudent type show 'Admin Notice' label. For adminTutor show 'Admin' label. - Clicking opens the chat view. **Rest Route** The `listMyConversations` API REST controller can be triggered via the following route: `/v1/myconversations` **Rest Request Parameters** The `listMyConversations` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/myconversations** ```js axios({ method: 'GET', url: '/v1/myconversations', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversations", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "conversations": [ { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "enrollment": [ { "coursePackId": "ID", "studentId": "ID", "tutorProfileId": "ID" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Send Systemmessage` API Interservice API called by adminPanel for moderation warnings. Creates/finds admin conversation with target user and sends a warning message. M2M only. **API Frontend Description By The Backend Architect** This API is not called from frontend. It is an interservice endpoint for adminPanel to deliver moderation warnings as chat messages. **Rest Route** The `sendSystemMessage` API REST controller can be triggered via the following route: `/v1/sendsystemmessage` **Rest Request Parameters** The `sendSystemMessage` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | targetUserId | ID | true | request.body?.["targetUserId"] | | targetUserRole | String | true | request.body?.["targetUserRole"] | | messageContent | Text | true | request.body?.["messageContent"] | | resolutionType | String | false | request.body?.["resolutionType"] | | complaintId | ID | false | request.body?.["complaintId"] | | severity | String | false | request.body?.["severity"] | **targetUserId** : The userId of the user to send the warning to **targetUserRole** : Role of target: student or tutor. Determines conversation type **messageContent** : The warning message content **resolutionType** : Moderation resolution type: warn, requireEdit, removeCourse, suspend, ban **complaintId** : Reference to original complaint/issue ID **severity** : Warning severity: info, warning, critical **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/sendsystemmessage** ```js axios({ method: 'POST', url: '/v1/sendsystemmessage', data: { targetUserId:"ID", targetUserRole:"String", messageContent:"Text", resolutionType:"String", complaintId:"ID", severity:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "conversation", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "conversation": { "id": "ID", "conversationType": "String", "conversationType_idx": "Integer", "participantA": "ID", "participantB": "ID", "enrollmentId": "ID", "lastMessageAt": "Date", "lastMessagePreview": "String", "status": "String", "status_idx": "Integer", "participantAName": "String", "participantBName": "String", "courseTitle": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Chatmessages` API **[Default list API]** — This is the designated default `list` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages in a chat hub room. Accessible by admins and room participants. **Rest Route** The `listChatMessages` API REST controller can be triggered via the following route: `/v1/v1/chat-messages` **Rest Request Parameters** **Filter Parameters** The `listChatMessages` api supports 9 optional filter parameters for filtering list results: **roomId** (`ID`): Reference to the room this message belongs to - Single: `?roomId=` - Multiple: `?roomId=&roomId=` - Null: `?roomId=null` **senderId** (`ID`): Reference to the user who sent this message - Single: `?senderId=` - Multiple: `?senderId=&senderId=` - Null: `?senderId=null` **senderName** (`String`): Display name of the sender (denormalized from user profile at send time) - Single (partial match, case-insensitive): `?senderName=` - Multiple: `?senderName=&senderName=` - Null: `?senderName=null` **senderAvatar** (`String`): Avatar URL of the sender (denormalized from user profile at send time) - Single (partial match, case-insensitive): `?senderAvatar=` - Multiple: `?senderAvatar=&senderAvatar=` - Null: `?senderAvatar=null` **messageType** (`Enum`): Content type discriminator for this message - Single: `?messageType=` (case-insensitive) - Multiple: `?messageType=&messageType=` - Null: `?messageType=null` **content** (`Object`): Type-specific content payload (structure depends on messageType) - Single: `?content=` - Multiple: `?content=&content=` - Null: `?content=null` **timestamp** (`String`): Message creation time - Single (partial match, case-insensitive): `?timestamp=` - Multiple: `?timestamp=×tamp=` - Null: `?timestamp=null` **status** (`Enum`): Message moderation status - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **replyTo** (`Object`): Reply thread reference { id, preview } - Single: `?replyTo=` - Multiple: `?replyTo=&replyTo=` - Null: `?replyTo=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages** ```js axios({ method: 'GET', url: '/v1/v1/chat-messages', data: { }, params: { // Filter parameters (see Filter Parameters section above) // roomId: '' // Filter by roomId // senderId: '' // Filter by senderId // senderName: '' // Filter by senderName // senderAvatar: '' // Filter by senderAvatar // messageType: '' // Filter by messageType // content: '' // Filter by content // timestamp: '' // Filter by timestamp // status: '' // Filter by status // replyTo: '' // Filter by replyTo } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "chatMessages": [ { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Chatmessage` API **[Default get API]** — This is the designated default `get` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single chat hub message by ID. **Rest Route** The `getChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `getChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to query the required data object. **id** : This parameter will be used to select the data object that is queried **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/v1/chat-messages/:id** ```js axios({ method: 'GET', url: `/v1/v1/chat-messages/${id}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Chatmessage` API **[Default delete API]** — This is the designated default `delete` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a chat hub message. Admins can delete any message; users can delete their own. **Rest Route** The `deleteChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `deleteChatMessage` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to select the required data object that will be deleted **id** : This parameter will be used to select the data object that want to be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/v1/chat-messages/:id** ```js axios({ method: 'DELETE', url: `/v1/v1/chat-messages/${id}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Chatmessage` API **[Default update API]** — This is the designated default `update` API for the `chatMessage` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a chat hub message content. Only the message sender or admins can edit. **Rest Route** The `updateChatMessage` API REST controller can be triggered via the following route: `/v1/v1/chat-messages/:id` **Rest Request Parameters** The `updateChatMessage` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | chatMessageId | ID | true | request.params?.["chatMessageId"] | | content | Object | false | request.body?.["content"] | | status | Enum | false | request.body?.["status"] | | id | String | true | request.params?.["id"] | **chatMessageId** : This id paremeter is used to select the required data object that will be updated **content** : Type-specific content payload (structure depends on messageType) **status** : Message moderation status **id** : This parameter will be used to select the data object that want to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/v1/chat-messages/:id** ```js axios({ method: 'PATCH', url: `/v1/v1/chat-messages/${id}`, data: { content:"Object", status:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "chatMessage", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "chatMessage": { "id": "ID", "roomId": "ID", "senderId": "ID", "senderName": "String", "senderAvatar": "String", "messageType": "Enum", "messageType_idx": "Integer", "content": "Object", "timestamp": null, "status": "Enum", "status_idx": "Integer", "replyTo": "Object", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## tutorhub-agenthub-service **Version:** `1.0.0` AI Agent Hub ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the AgentHub Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AgentHub Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the AgentHub Service via HTTP requests for purposes such as creating, updating, deleting and querying AgentHub objects. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. Beyond REST It's important to note that the AgentHub Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. ## Authentication And Authorization To ensure secure access to the AgentHub service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes: **Protected API**: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected. **Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token. ### Token Locations When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters. | Location | Token Name / Param Name | | ---------------------- | ---------------------------- | | Query | access_token | | Authorization Header | Bearer | | Header | tutorhub-access-token| | Cookie | tutorhub-access-token| Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies. ## Api Definitions This section outlines the API endpoints available within the AgentHub service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the AgentHub service. This service is configured to listen for HTTP requests on port `3006`, serving both the main API interface and default administrative endpoints. The following routes are available by default: * **API Test Interface (API Face):** `/` * **Swagger Documentation:** `/swagger` * **Postman Collection Download:** `/getPostmanCollection` * **Health Checks:** `/health` and `/admin/health` * **Current Session Info:** `/currentuser` * **Favicon:** `/favicon.ico` This service is accessible via the following environment-specific URLs: * **Preview:** `https://tutorhub.prw.mindbricks.com/agenthub-api` * **Staging:** `https://tutorhub-stage.mindbricks.co/agenthub-api` * **Production:** `https://tutorhub.mindbricks.co/agenthub-api` **Parameter Inclusion Methods:** Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests: **Query Parameters:** Included directly in the URL's query string. **Path Parameters:** Embedded within the URL's path. **Body Parameters:** Sent within the JSON body of the request. **Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request. **Note on Session Parameters:** Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request. By adhering to the specified parameter inclusion methods, you can effectively utilize the AgentHub service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below. ### Common Parameters The `AgentHub` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL. ### Supported Common Parameters: - **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations. - **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage. - **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters. - **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache. - **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs. - **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`. - **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request. By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `AgentHub` service. ### Error Response If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity: - **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it. - **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource. - **404 Not Found**: The requested resource was not found on the server. - **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request. Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ```` ### Object Structure of a Successfull Response When the `AgentHub` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client. **Key Characteristics of the Response Envelope:** - **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope. - **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects. - **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form. - **Get Requests**: A single data object is returned in JSON format. - **Get List Requests**: An array of data objects is provided, reflecting a collection of resources. - **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters. - **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions. - **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services. - **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects. **Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information. **Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect. ### API Response Structure The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response. **HTTP Status Codes:** - **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully. - **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3 "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ```` - **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed. **Handling Errors:** For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages. ## Resources AgentHub service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service. ### Sys_agentOverride resource *Resource Definition* : Runtime overrides for design-time agents. Null fields use the design default. *Sys_agentOverride Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **agentName** | String | | | *Design-time agent name this override applies to.* | | **provider** | String | | | *Override AI provider (e.g., openai, anthropic).* | | **model** | String | | | *Override model name.* | | **systemPrompt** | Text | | | *Override system prompt.* | | **temperature** | Double | | | *Override temperature (0-2).* | | **maxTokens** | Integer | | | *Override max tokens.* | | **responseFormat** | String | | | *Override response format (text/json).* | | **selectedTools** | Object | | | *Array of tool names from the catalog that this agent can use.* | | **guardrails** | Object | | | *Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.* | | **enabled** | Boolean | | | *Enable or disable this agent.* | | **updatedBy** | ID | | | *User who last updated this override.* | ### Sys_agentExecution resource *Resource Definition* : Agent execution log. Records each agent invocation with input, output, and performance metrics. *Sys_agentExecution Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **agentName** | String | | | *Agent that was executed.* | | **agentType** | Enum | | | *Whether this was a design-time or dynamic agent.* | | **source** | Enum | | | *How the agent was triggered.* | | **userId** | ID | | | *User who triggered the execution.* | | **input** | Object | | | *Request input (truncated for large payloads).* | | **output** | Object | | | *Response output (truncated for large payloads).* | | **toolCalls** | Integer | | | *Number of tool calls made during execution.* | | **tokenUsage** | Object | | | *Token usage: { prompt, completion, total }.* | | **durationMs** | Integer | | | *Execution time in milliseconds.* | | **status** | Enum | | | *Execution status.* | | **error** | Text | | | *Error message if execution failed.* | #### Enum Properties Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer. ##### agentType Enum Property *Property Definition* : Whether this was a design-time or dynamic agent.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **design** | `"design""` | 0 | | **dynamic** | `"dynamic""` | 1 | ##### source Enum Property *Property Definition* : How the agent was triggered.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **rest** | `"rest""` | 0 | | **sse** | `"sse""` | 1 | | **kafka** | `"kafka""` | 2 | | **agent** | `"agent""` | 3 | ##### status Enum Property *Property Definition* : Execution status.*Enum Options* | Name | Value | Index | | ---- | ----- | ----- | | **success** | `"success""` | 0 | | **error** | `"error""` | 1 | | **timeout** | `"timeout""` | 2 | ### Sys_toolCatalog resource *Resource Definition* : Cached tool catalog discovered from project services. Refreshed periodically. *Sys_toolCatalog Resource Properties* | Name | Type | Required | Default | Definition | | ---- | ---- | -------- | ------- | ---------- | | **toolName** | String | | | *Full tool name (e.g., service:apiName).* | | **serviceName** | String | | | *Source service name.* | | **description** | Text | | | *Tool description.* | | **parameters** | Object | | | *JSON Schema of tool parameters.* | | **lastRefreshed** | Date | | | *When this tool was last discovered/refreshed.* | ## Business Api ### `Get Agentoverride` API **[Default get API]** — This is the designated default `get` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `getAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'GET', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentoverrides` API **[Default list API]** — This is the designated default `list` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentOverrides` API REST controller can be triggered via the following route: `/v1/agentoverrides` **Rest Request Parameters** The `listAgentOverrides` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverrides** ```js axios({ method: 'GET', url: '/v1/agentoverrides', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverrides", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentOverrides": [ { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Agentoverride` API **[Default update API]** — This is the designated default `update` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `updateAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `updateAgentOverride` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | | provider | String | | request.body?.["provider"] | | model | String | | request.body?.["model"] | | systemPrompt | Text | | request.body?.["systemPrompt"] | | temperature | Double | | request.body?.["temperature"] | | maxTokens | Integer | | request.body?.["maxTokens"] | | responseFormat | String | | request.body?.["responseFormat"] | | selectedTools | Object | | request.body?.["selectedTools"] | | guardrails | Object | | request.body?.["guardrails"] | | enabled | Boolean | | request.body?.["enabled"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be updated **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **enabled** : Enable or disable this agent. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'PATCH', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", enabled:"Boolean", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Create Agentoverride` API **[Default create API]** — This is the designated default `create` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `createAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride` **Rest Request Parameters** The `createAgentOverride` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | agentName | String | true | request.body?.["agentName"] | | provider | String | false | request.body?.["provider"] | | model | String | false | request.body?.["model"] | | systemPrompt | Text | false | request.body?.["systemPrompt"] | | temperature | Double | false | request.body?.["temperature"] | | maxTokens | Integer | false | request.body?.["maxTokens"] | | responseFormat | String | false | request.body?.["responseFormat"] | | selectedTools | Object | false | request.body?.["selectedTools"] | | guardrails | Object | false | request.body?.["guardrails"] | **agentName** : Design-time agent name this override applies to. **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/agentoverride** ```js axios({ method: 'POST', url: '/v1/agentoverride', data: { agentName:"String", provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Delete Agentoverride` API **[Default delete API]** — This is the designated default `delete` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `deleteAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'DELETE', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `List Toolcatalog` API **[Default list API]** — This is the designated default `list` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listToolCatalog` API REST controller can be triggered via the following route: `/v1/toolcatalog` **Rest Request Parameters** **Filter Parameters** The `listToolCatalog` api supports 1 optional filter parameter for filtering list results: **serviceName** (`String`): Source service name. - Single (partial match, case-insensitive): `?serviceName=` - Multiple: `?serviceName=&serviceName=` - Null: `?serviceName=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalog** ```js axios({ method: 'GET', url: '/v1/toolcatalog', data: { }, params: { // Filter parameters (see Filter Parameters section above) // serviceName: '' // Filter by serviceName } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_toolCatalogs": [ { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Toolcatalogentry` API **[Default get API]** — This is the designated default `get` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getToolCatalogEntry` API REST controller can be triggered via the following route: `/v1/toolcatalogentry/:sys_toolCatalogId` **Rest Request Parameters** The `getToolCatalogEntry` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_toolCatalogId | ID | true | request.params?.["sys_toolCatalogId"] | **sys_toolCatalogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalogentry/:sys_toolCatalogId** ```js axios({ method: 'GET', url: `/v1/toolcatalogentry/${sys_toolCatalogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_toolCatalog": { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentexecutions` API **[Default list API]** — This is the designated default `list` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentExecutions` API REST controller can be triggered via the following route: `/v1/agentexecutions` **Rest Request Parameters** **Filter Parameters** The `listAgentExecutions` api supports 5 optional filter parameters for filtering list results: **agentName** (`String`): Agent that was executed. - Single (partial match, case-insensitive): `?agentName=` - Multiple: `?agentName=&agentName=` - Null: `?agentName=null` **agentType** (`Enum`): Whether this was a design-time or dynamic agent. - Single: `?agentType=` (case-insensitive) - Multiple: `?agentType=&agentType=` - Null: `?agentType=null` **source** (`Enum`): How the agent was triggered. - Single: `?source=` (case-insensitive) - Multiple: `?source=&source=` - Null: `?source=null` **userId** (`ID`): User who triggered the execution. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **status** (`Enum`): Execution status. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecutions** ```js axios({ method: 'GET', url: '/v1/agentexecutions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // agentName: '' // Filter by agentName // agentType: '' // Filter by agentType // source: '' // Filter by source // userId: '' // Filter by userId // status: '' // Filter by status } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecutions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentExecutions": [ { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Agentexecution` API **[Default get API]** — This is the designated default `get` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentExecution` API REST controller can be triggered via the following route: `/v1/agentexecution/:sys_agentExecutionId` **Rest Request Parameters** The `getAgentExecution` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentExecutionId | ID | true | request.params?.["sys_agentExecutionId"] | **sys_agentExecutionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecution/:sys_agentExecutionId** ```js axios({ method: 'GET', url: `/v1/agentexecution/${sys_agentExecutionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecution", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentExecution": { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### Authentication Specific Routes ### Common Routes ### Route: currentuser *Route Definition*: Retrieves the currently authenticated user's session information. *Route Type*: sessionInfo *Access Route*: `GET /currentuser` #### Parameters This route does **not** require any request parameters. #### Behavior - Returns the authenticated session object associated with the current access token. - If no valid session exists, responds with a 401 Unauthorized. ```js // Sample GET /currentuser call axios.get("/currentuser", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns the session object, including user-related data and token information. ```` { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", ... } ```` **Error Response** **401 Unauthorized:** No active session found. ```` { "status": "ERR", "message": "No login found" } ```` **Notes** * This route is typically used by frontend or mobile applications to fetch the current session state after login. * The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests. * Always ensure a valid access token is provided in the request to retrieve the session. ### Route: permissions `*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user. `*Route Type*`: permissionFetch *Access Route*: `GET /permissions` #### Parameters This route does **not** require any request parameters. #### Behavior - Fetches all active permission records (`givenPermissions` entries) associated with the current user session. - Returns a full array of permission objects. - Requires a valid session (`access token`) to be available. ```js // Sample GET /permissions call axios.get("/permissions", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** Returns an array of permission objects. ```json [ { "id": "perm1", "permissionName": "adminPanel.access", "roleId": "admin", "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" }, { "id": "perm2", "permissionName": "orders.manage", "roleId": null, "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "subjectUserGroupId": null, "objectId": null, "canDo": true, "tenantCodename": "store123" } ] ```` Each object reflects a single permission grant, aligned with the givenPermissions model: - `**permissionName**`: The permission the user has. - `**roleId**`: If the permission was granted through a role. -` **subjectUserId**`: If directly granted to the user. - `**subjectUserGroupId**`: If granted through a group. - `**objectId**`: If tied to a specific object (OBAC). - `**canDo**`: True or false flag to represent if permission is active or restricted. **Error Responses** * **401 Unauthorized**: No active session found. ```json { "status": "ERR", "message": "No login found" } ```` * **500 Internal Server Error**: Unexpected error fetching permissions. **Notes** * The /permissions route is available across all backend services generated by Mindbricks, not just the auth service. * Auth service: Fetches permissions freshly from the live database (givenPermissions table). * Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks. > **Tip**: > Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations. ### Route: permissions/:permissionName *Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions. *Route Type*: permissionScopeCheck *Access Route*: `GET /permissions/:permissionName` #### Parameters | Parameter | Type | Required | Population | |------------------|--------|----------|------------------------| | permissionName | String | Yes | `request.params.permissionName` | #### Behavior - Evaluates whether the current user **has access** to the given `permissionName`. - Returns a structured object indicating: - Whether the permission is generally granted (`canDo`) - Which object IDs are explicitly included or excluded from access (`exceptions`) - Requires a valid session (`access token`). ```js // Sample GET /permissions/orders.manage axios.get("/permissions/orders.manage", { headers: { "Authorization": "Bearer your-jwt-token" } }); ```` **Success Response** ```json { "canDo": true, "exceptions": [ "a1f2e3d4-xxxx-yyyy-zzzz-object1", "b2c3d4e5-xxxx-yyyy-zzzz-object2" ] } ```` * If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions). * If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides). * The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission). ## Copyright All sources, documents and other digital materials are copyright of . ## About Us For more information please visit our website: . . . --- # REST API GUIDE ## BFF SERVICE **Version:** `1.0.21` BFF service is a microservice that acts as a bridge between the client and the backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to. For inquiries, feedback, or further information regarding the architecture, please direct your communication to: Email: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the BFF Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our BFF Service exclusively through RESTful API endpoints. **Intended Audience** This documentation is intended for developers and integrators who are looking to interact with the BFF Service via HTTP requests for purposes such as listing, filtering, and searching data. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. **Beyond REST** It's important to note that the BFF Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. --- ## Resources ### Elastic Index Resource _Resource Definition_: A virtual resource representing dynamic search data from a specified index. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/:indexName/list` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-----------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ```

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

--- _Default access route_: _GET_ `/:indexName/list` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-----------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/${indexName}/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/:indexName/count` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/:indexName/count` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | q | String | No | query.q | ```js axios({ method: "GET", url: `/${indexName}/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/:indexName/schema` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | ```js axios({ method: "GET", url: `/${indexName}/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /:indexName/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | page | Number | No | query.page | | limit | Number | No | query.limit | ```js axios({ method: "GET", url: `/${indexName}/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /:indexName/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/${indexName}/filters`, data: { filterName: "String", conditions: "Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /:indexName/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | filterId | String | Yes | path.param | ```js axios({ method: "DELETE", url: `/${indexName}/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/:indexName/:id` ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | indexName | String | Yes | path.param | | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/${indexName}/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/studentEnrollmentDashboardView` **Example**: ```js axios({ method: "GET", url: `/studentEnrollmentDashboardView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/studentEnrollmentDashboardView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/studentEnrollmentDashboardView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/tutorDashboardCoursesView` **Example**: ```js axios({ method: "GET", url: `/tutorDashboardCoursesView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/tutorDashboardCoursesView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/tutorDashboardCoursesView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/enrollmentNotificationView` **Example**: ```js axios({ method: "GET", url: `/enrollmentNotificationView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/enrollmentNotificationView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/enrollmentNotificationView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/refundNotificationView` **Example**: ```js axios({ method: "GET", url: `/refundNotificationView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/refundNotificationView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/refundNotificationView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/preliminaryScreeningDecisionView` **Example**: ```js axios({ method: "GET", url: `/preliminaryScreeningDecisionView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/preliminaryScreeningDecisionView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/preliminaryScreeningDecisionView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/enrollmentRequiresScreeningView` **Example**: ```js axios({ method: "GET", url: `/enrollmentRequiresScreeningView`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/enrollmentRequiresScreeningView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/enrollmentRequiresScreeningView/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get All Aggregated Records _Route Definition_: Retrieves a full list of aggregated view data. _Route Type_: list _Default access route_: _GET_ `/deneme` **Example**: ```js axios({ method: "GET", url: `/deneme`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Single Aggregated Record _Route Definition_: Retrieves a specific aggregated document by ID. _Route Type_: get _Default access route_: _GET_ `/deneme/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/deneme/${id}`, data: {}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/publicTutorProfileView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicTutorProfileView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/publicTutorProfileView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicTutorProfileView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/publicTutorProfileView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicTutorProfileView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/publicTutorProfileView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicTutorProfileView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/publicTutorProfileView/schema` ```js axios({ method: "GET", url: `/publicTutorProfileView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /publicTutorProfileView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/publicTutorProfileView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /publicTutorProfileView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicTutorProfileView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /publicTutorProfileView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/publicTutorProfileView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/publicTutorProfileView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/publicTutorProfileView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/publicCoursePackView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCoursePackView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/publicCoursePackView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicCoursePackView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/publicCoursePackView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCoursePackView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/publicCoursePackView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicCoursePackView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/publicCoursePackView/schema` ```js axios({ method: "GET", url: `/publicCoursePackView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /publicCoursePackView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/publicCoursePackView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /publicCoursePackView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCoursePackView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /publicCoursePackView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/publicCoursePackView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/publicCoursePackView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/publicCoursePackView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/issueReportStatusChangedView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/issueReportStatusChangedView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/issueReportStatusChangedView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/issueReportStatusChangedView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/issueReportStatusChangedView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/issueReportStatusChangedView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/issueReportStatusChangedView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/issueReportStatusChangedView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/issueReportStatusChangedView/schema` ```js axios({ method: "GET", url: `/issueReportStatusChangedView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /issueReportStatusChangedView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/issueReportStatusChangedView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /issueReportStatusChangedView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/issueReportStatusChangedView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /issueReportStatusChangedView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/issueReportStatusChangedView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/issueReportStatusChangedView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/issueReportStatusChangedView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/contentModerationActionView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/contentModerationActionView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/contentModerationActionView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/contentModerationActionView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/contentModerationActionView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/contentModerationActionView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/contentModerationActionView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/contentModerationActionView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/contentModerationActionView/schema` ```js axios({ method: "GET", url: `/contentModerationActionView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /contentModerationActionView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/contentModerationActionView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /contentModerationActionView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/contentModerationActionView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /contentModerationActionView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/contentModerationActionView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/contentModerationActionView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/contentModerationActionView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/adminDashboardStatsView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/adminDashboardStatsView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/adminDashboardStatsView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/adminDashboardStatsView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/adminDashboardStatsView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/adminDashboardStatsView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/adminDashboardStatsView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/adminDashboardStatsView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/adminDashboardStatsView/schema` ```js axios({ method: "GET", url: `/adminDashboardStatsView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /adminDashboardStatsView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/adminDashboardStatsView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /adminDashboardStatsView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/adminDashboardStatsView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /adminDashboardStatsView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/adminDashboardStatsView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/adminDashboardStatsView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/adminDashboardStatsView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- ## Route: List Records _Route Definition_: Returns a paginated list from the elastic index. _Route Type_: list _Default access route_: _POST_ `/publicCourseCategoryView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCourseCategoryView/list`, data: { filters: "Object" }, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/publicCourseCategoryView/list` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-----------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy | | sortOrder | String | No | query.sortOrder | | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicCourseCategoryView/list`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String", sortOrder: "String", q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Count Records _Route Definition_: Counts matching documents in the elastic index. _Route Type_: count _Default access route_: _POST_ `/publicCourseCategoryView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCourseCategoryView/count`, data: { filters: "Object" }, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- _Default access route_: _GET_ `/publicCourseCategoryView/count` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | q | String | No | query.q | ```js axios({ method: "GET", url: `/publicCourseCategoryView/count`, data:{}, params: { q: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get Index Schema _Route Definition_: Returns the schema for the elastic index. _Route Type_: get _Default access route_: _GET_ `/publicCourseCategoryView/schema` ```js axios({ method: "GET", url: `/publicCourseCategoryView/schema`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Filters ### GET /publicCourseCategoryView/filters _Route Type_: get ### Parameters | Parameter | Type | Required | Population| |----------|--------|----------|------------| | page | Number | No | query.page | | limit | Number | No | query.limit| ```js axios({ method: "GET", url: `/publicCourseCategoryView/filters`, data:{}, params: { page: "Number", limit: "Number" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### POST /publicCourseCategoryView/filters _Route Type_: create ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filters | Object | Yes | body | ```js axios({ method: "POST", url: `/publicCourseCategoryView/filters`, data: { "filters":"Object" }, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ### DELETE /publicCourseCategoryView/filters/:filterId _Route Type_: delete ### Parameters | Parameter | Type | Required | Population | |-------------|--------|----------|-------------| | filterId | ID | Yes | path.param | ```js axios({ method: "DELETE", url: `/publicCourseCategoryView/filters/${filterId}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. ## Route: Get One Record _Route Type_: get _Default access route_: _GET_ `/publicCourseCategoryView/:id` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|----------------| | id | ID | Yes | path.param | ```js axios({ method: "GET", url: `/publicCourseCategoryView/${id}`, data:{}, params: {} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. --- --- # REST API GUIDE ## NOTIFICATION SERVICE **Version:** `1.0.111` The Notification service is a microservice that allows sending notifications through SMS, Email, and Push channels. Providers can be configured dynamically through the `.env` file. ## Architectural Design Credit and Contact Information The architectural design of this microservice is credited to. For inquiries, feedback, or further information regarding the architecture, please direct your communication to: **Email**: We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice. ## Documentation Scope Welcome to the official documentation for the Notification Service REST API. This document provides a comprehensive overview of the available endpoints, how they work, and how to use them efficiently. **Intended Audience** This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the Notification Service. It assumes familiarity with microservices architecture and RESTful APIs. **Overview** Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases. **Beyond REST** It's important to note that the Notification Service also supports alternative methods of interaction, such as messaging via a Kafka message broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation. --- ## Routes ### Route: Register Device _Route Definition_: Registers a device for a user. _Route Type_: create _Default access route_: _POST_ `/devices/register` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | device | Object | Yes | body | | userId | ID | Yes | req.userId | ```js axios({ method: "POST", url: `/devices/register`, data: { device:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Unregister Device _Route Definition_: Removes a registered device. _Route Type_: delete _Default access route_: _DELETE_ `/devices/unregister/:deviceId` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | deviceId | ID | Yes | path.param | | userId | ID | Yes | req.userId | ```js axios({ method: "DELETE", url: `/devices/unregister/${deviceId}`, data:{}, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Get Notifications _Route Definition_: Retrieves a paginated list of notifications. _Route Type_: get _Default access route_: _GET_ `/notifications` ### Parameters | Parameter | Type | Required | Population | |-----------|--------|----------|-------------| | page | Number | No | query.page | | limit | Number | No | query.limit | | sortBy | String | No | query.sortBy| | userId | ID | Yes | req.userId | ```js axios({ method: "GET", url: `/notifications`, data:{}, params: { page: "Number", limit: "Number", sortBy: "String" } }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Send Notification _Route Definition_: Sends a notification to specified recipients. _Route Type_: create _Default access route_: _POST_ `/notifications` ### Parameters | Parameter | Type | Required | Population | |---------------|--------|----------|------------| |notification | Object | Yes | body | ```js axios({ method: "POST", url: `/notifications`, data: { notification:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. ### Route: Mark Notifications as Seen _Route Definition_: Marks selected notifications as seen. _Route Type_: update _Default access route_: _POST_ `/notifications/seen` ### Parameters | Parameter | Type | Required | Population | |------------------ |--------|----------|------------| | notificationIds | Array | Yes | body | | userId | ID | Yes | req.userId | ```js axios({ method: "POST", url: `/notifications/seen`, data: { notificationIds:"Object" }, params:{} }); ``` The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a `"status": "OK"` property. Any validation errors will return status code `400` with an error message. --- --- --- *Generated by Mindbricks Genesis Engine*