# AuteurLabb Networking Platform - Frontend Development Prompts > AI-assisted frontend development prompts for AuteurLabb Networking Platform This document contains all frontend development prompts that can be used to build the user interface for this project. Each prompt provides detailed specifications for implementing specific frontend features. --- ## Table of Contents - [Introduction](#introduction) - [Project Introduction & Setup](#frontend-prompts-frontend-prompt-1-projectintroduction) - [Authentication Management](#frontend-prompts-frontend-prompt-2-authmanagement) - [Verification Management](#frontend-prompts-frontend-prompt-3-verification) - [Profile Management](#frontend-prompts-frontend-prompt-4-profile) - [User Management](#frontend-prompts-frontend-prompt-5-usermanagement) - [MCP BFF Integration](#frontend-prompts-frontend-prompt-6-mcpbffintegration) - [ProjectPortfolio Service](#frontend-prompts-frontend-prompt-7-projectportfolioservice) - [MessagingCenter Service](#frontend-prompts-frontend-prompt-8-messagingcenterservice) - [ModerationAdmin Service](#frontend-prompts-frontend-prompt-9-moderationadminservice) - [AgentHub Service](#frontend-prompts-frontend-prompt-10-agenthubservice) --- ## Introduction ### Project Overview # AuteurLabb Networking Platform Version : 1.0.71 AuteurLabb is a networking platform that connects filmmakers, studios, investors, and supporters to collaborate on film projects with secure access and role-based workflows. ## How to Use Project Documents The `Auteurlabb` 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://auteurlabb.prw.mindbricks.com/auth-api` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/auth-api` | | **Production** | `https://auteurlabb.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 `Auteurlabb` 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 `AuteurLabb Networking 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 ### projectPortfolio Service **Description:** Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership. **Documentation:** * [REST API Guide](/document/docs/projectPortfolio-service/rest-api-guide.html) * [Event Guide](/document/docs/projectPortfolio-service/event-guide.html) * [Service Design](/document/docs/projectPortfolio-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://auteurlabb.prw.mindbricks.com/projectportfolio-api` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/projectportfolio-api` | | **Production** | `https://auteurlabb.mindbricks.co/projectportfolio-api` | ### messagingCenter Service **Description:** Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations. **Documentation:** * [REST API Guide](/document/docs/messagingCenter-service/rest-api-guide.html) * [Event Guide](/document/docs/messagingCenter-service/event-guide.html) * [Service Design](/document/docs/messagingCenter-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://auteurlabb.prw.mindbricks.com/messagingcenter-api` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/messagingcenter-api` | | **Production** | `https://auteurlabb.mindbricks.co/messagingcenter-api` | ### moderationAdmin Service **Description:** Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance. **Documentation:** * [REST API Guide](/document/docs/moderationAdmin-service/rest-api-guide.html) * [Event Guide](/document/docs/moderationAdmin-service/event-guide.html) * [Service Design](/document/docs/moderationAdmin-service/service-design.html) **Base URL Examples:** | Environment | URL | |-------------|---------------------| | **Preview** | `https://auteurlabb.prw.mindbricks.com/moderationadmin-api` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/moderationadmin-api` | | **Production** | `https://auteurlabb.mindbricks.co/moderationadmin-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://auteurlabb.prw.mindbricks.com/agenthub-api` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/agenthub-api` | | **Production** | `https://auteurlabb.mindbricks.co/agenthub-api` | ## Connect via MCP (Model Context Protocol) All backend services in the `Auteurlabb` 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://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp` | `https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp/sse` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/mcpbff-api/mcp` | `https://auteurlabb-stage.mindbricks.co/mcpbff-api/mcp/sse` | | **Production** | `https://auteurlabb.mindbricks.co/mcpbff-api/mcp` | `https://auteurlabb.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": { "auteurlabb": { "url": "https://auteurlabb.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": { "auteurlabb": { "url": "https://auteurlabb.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 `AuteurLabb Networking Platform` backend, generated by the Mindbricks platform. It is structured to support both AI agents and human developers in navigating authentication, data access, service responsibilities, and system architecture. To summarize: * Start with the **Auth Service** to manage users, roles, sessions, and permissions. * Use the **BFF Service** for optimized, read-only data queries and cross-service aggregation. * Refer to the **Business Services** when you need to manage domain-specific data or perform direct CRUD operations. Each service offers a complete set of documentation—REST API guides, event interface definitions, and design insights—to help you integrate efficiently and confidently. Whether you are building a frontend application, configuring an automation agent, or simply exploring the architecture, this documentation is your primary reference for working with the backend of this project. > For environment-specific access, ensure you're using the correct base URLs (Preview, Staging, Production), and coordinate with the project owner for any custom deployments. --- ### How to Use These Prompts These prompts are designed to be used with AI coding assistants to help build frontend features. Each prompt includes: 1. **Feature Description** - What the feature does and its purpose 2. **Data Models** - The backend data structures to work with 3. **API Endpoints** - Available REST APIs for the feature 4. **UI Requirements** - Specific user interface requirements 5. **Implementation Guidelines** - Best practices and patterns to follow When using these prompts with an AI assistant: - Copy the relevant prompt section - Provide context about your frontend framework (React, Vue, Angular, etc.) - Reference the REST API documentation for endpoint details --- ## Frontend Development Prompts # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Project Introduction & Setup** This is the introductory document for the **auteurlabb** frontend project. It is designed for AI agents that will generate frontend code to consume the project's backend. Read it carefully — it describes the project scope, architecture, API conventions, and initial screens you must build before proceeding to the feature-specific prompts that follow. This prompt will help you set up the project infrastructure, create the initial layout, home page, navigation, and any dummy screens. The subsequent prompts will provide detailed API documentation for each feature area. ## Project Introduction AuteurLabb is a networking platform that connects filmmakers, studios, investors, and supporters to collaborate on film projects with secure access and role-based workflows. ## Project Services Overview The project has **1 auth service**, **1 notification service**, **1 BFF service**, and **4 business services**, plus other helper services such as bucket and realtime. Each service is a separate microservice application and listens for HTTP requests at different service URLs. | # | Service | Description | API Prefix | |---|---------|-------------|------------| | 1 | auth | Authentication and user management | `/auth-api` | | 2 | projectPortfolio | Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership. | `/projectPortfolio-api` | | 3 | messagingCenter | Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations. | `/messagingCenter-api` | | 4 | moderationAdmin | Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance. | `/moderationAdmin-api` | | 5 | agentHub | AI Agent Hub | `/agentHub-api` | Detailed API documentation for each service will be given in the following prompts. In this document, you will build the initial project structure, home pages, and navigation. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API's response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## Accessing the Backend Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services. The base URL of the application in each environment is as follows: * **Preview:** `https://auteurlabb.prw.mindbricks.com` * **Staging:** `https://auteurlabb-stage.mindbricks.co` * **Production:** `https://auteurlabb.mindbricks.co` For the auth service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/auth-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/auth-api` * **Production:** `https://auteurlabb.mindbricks.co/auth-api` For each other service, append `/{serviceName}-api` to the environment base URL. Any request that requires login must include a valid token in the Bearer authorization header. Please note that for each service in the project (which will be introduced in following prompts) will use a different address so it is a good practice to define a separate client for each service in the frontend application lib source. Not only the different base urls, some services even may need different access rules when shaping the request. Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page. ## Home Page First build a home page which shows some static content about the application, and has got login and registration (if is public) buttons. The home page should be updated later according to the content that each service provides, as a frontend developer use best and common practices to reflect the service content to the home page. User may also give extra information for the home page content in addition to this prompt. Note that this page should include a deployment (environment) selection option to set the base URL. Set the default to `production`. After user logs in, page header should show the current login state as in modern web pages, logged in user fullname, avatar, email and with a logout link, make a fancy current user component. The home page may have different views before and after login. ## Initial Navigation Structure Build the initial navigation/sidebar with placeholder pages for each area of the application. These will be implemented in detail by the subsequent prompts: - Home / Landing - Login - Register - Profile - User Management (admin) - ProjectPortfolio Service Pages - MessagingCenter Service Pages - ModerationAdmin Service Pages - AgentHub Service Pages Create these as placeholder/dummy pages with a title and "Coming soon" note. They will be filled in by the following prompts. ## What To Build Now With this prompt, build: 1. **Project infrastructure** — routing, layout, environment config, API client setup (one client per service) 2. **Home page** with environment selector, login/register buttons, project description 4. **Placeholder pages** for all navigation items listed above 5. **Common components** — header with user info, navigation sidebar/menu, layout wrapper Do **not** implement authentication flows, registration, or any service-specific features yet — those will be covered in the next prompts. ## Common Reminders 1. When the application starts, please ensure that the `baseUrl` is set to the production server URL, and that the environment selector dropdown has the **Production** option selected by default. 2. Note that any API call to the application backend is based on a service base URL. Auth APIs use `/auth-api` prefix, and each business service uses `/{serviceName}-api` prefix after the application's base URL. 3. The deployment environment selector will only be used in the home page. If any page is called directly bypassing the home page, the page will use the stored or default environment. --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Authentication Management** This document covers the authentication features of the **auteurlabb** project: registration, login, logout, and session management. The project introduction, API conventions, base URLs, home page, and multi-tenancy setup were covered in the previous introductory prompt — make sure those are implemented before proceeding. All auth APIs use the auth service base URL with the `/auth-api` prefix (e.g., `https://auteurlabb.mindbricks.co/auth-api`). ### FRONTEND_URL The `FRONTEND_URL` environment variable is automatically set on the auth service from the project's **frontendUrl** setting in Basic Project Settings. It contains the base URL of the frontend application for the current deployment environment (e.g., `http://localhost:5173` for dev, `https://myapp.com` for production). Defaults if not configured: | Environment | Default | |-------------|---------| | dev | `http://localhost:5173` | | test | `https://auteurlabb.prw.mindbricks.com` | | stage | `https://auteurlabb-stage.mindbricks.co` | | prod | `https://auteurlabb.mindbricks.co` | This variable is used by the auth service for: - **Social login redirects** — after OAuth processing, the auth service redirects to `FRONTEND_URL + /auth/callback` (the frontend must have a page at this route; see the Social Login prompt for details) - **Email notification links** — verification, password reset, and other links in emails point back to the frontend You can customize `FRONTEND_URL` per environment by configuring the `frontendUrl` field in your project's Basic Project Settings (e.g., when using a custom domain). ## Registration Management ### User Registration User registration is public in the application. Please create a simple and polished registration page that includes only the necessary fields of the registration API. Using the `registeruser` route of the auth API, send the required fields from your registration page. The `registerUser` API in the `auth` service is described with the request and response structure below. Note that since the `registerUser` API is a business API, it is versioned; call it with the given version like `/v1/registeruser`. ### `Register User` API This api is used by public users to register themselves **Rest Route** The `registerUser` API REST controller can be triggered via the following route: `/v1/registeruser` **Rest Request Parameters** The `registerUser` api has got 4 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"] | **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. **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", }, 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", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` After a successful registration, the frontend code should handle any verification requirements. Verification Management will be given in the next prompt. The registration response will include a `user` object in the root envelope; this object contains user information with an `id` field. ## Login Management ### Login Identifier Model The **primary login identifier** for this application is the **email address**. Users register and log in using their email and password. No mobile field is stored in the user data model. The login page should include an email input and a password input. ### Login Flow After successful registration and completing any required verifications, the user can log in. Please create a minimal, polished login page as described above. Note that this page should respect the deployment (environment) selection option made in the home page to set the base URL. If the user reaches this page directly skipping home page, the default `production` deployment will be used. The login API returns a created session. This session can be retrieved later with the access token using the `/currentuser` system route. Any request that requires login must include a valid token. When a user logs in successfully, the response JSON includes a JWT access token in the `accessToken` field. Under normal conditions, this token is also set as a cookie and consumed automatically. However, since AI coding agents' preview options may fail to use cookies, ensure that each request includes the access token in the Bearer authorization header. If the login fails due to verification requirements, the response JSON includes an `errCode`. If it is `EmailVerificationNeeded`, start the email verification flow; if it is `MobileVerificationNeeded`, start the mobile verification flow. After a successful login, you can access session (user) information at any time with the `/currentuser` API. On inner pages, show brief profile information (avatar, name, etc.) using the session information from this API. Note that the `currentuser` API returns a session object, so there is no `id` property; instead, the values for the user and session are exposed as `userId` and `sessionId`. The response combines user and session information. The login, logout, and currentuser APIs are as follows. They are system routes and are not versioned. ### `POST /login` — User Login **Purpose:** Verifies user credentials and creates an authenticated session with a JWT access token. **Access Routes:** #### Request Parameters | Parameter | Type | Required | Source | | ---------- | ------ | -------- | ----------------------- | | `username` | String | Yes | `request.body.username` | | `password` | String | Yes | `request.body.password` | #### Behavior * Authenticates credentials and returns a session object. * Sets cookie: `projectname-access-token[-tenantCodename]` * Adds the same token in response headers. * Accepts either `username` or `email` fields (if both exist, `username` is prioritized). The `mobile` field is also accepted when the user has a mobile number on file. #### Example ```js axios.post("/login", { email: "user@example.com", password: "securePassword" }); ``` #### Success Response ```json { "sessionId": "e81c7d2b-4e95-9b1e-842e-3fb9c8c1df38", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", //... "accessToken": "ey7....", "userBucketToken": "e56d....", "sessionNeedsEmail2FA": true, "sessionNeedsMobile2FA": true, } ``` > **Note on bucket tokens:** The `userBucketToken` is for the **external bucket service** (used for general file uploads like documents and product images). **User avatars do not use the external bucket service** — they are uploaded via database buckets (dbBuckets) built into the auth service using the regular `accessToken`. See the Profile or Bucket Management sections for dbBucket avatar upload details. > **Two-Factor Authentication (2FA):** When the login response contains `sessionNeedsEmail2FA: true or sessionNeedsMobile2FA: true`, the session is **not yet fully authorized**. The `accessToken` is valid but all protected API calls will return `403` until 2FA is completed. **Do not treat this login as successful** — instead, store the `accessToken`, `userId`, and `sessionId`, and navigate the user to a 2FA verification page. The 2FA flow details are covered in the **Verification Management** prompt. ### Error Responses * `401 Unauthorized`: Invalid credentials * `403 Forbidden`: Email/mobile verification or 2FA pending * `400 Bad Request`: Missing parameters --- ### `POST /logout` — User Logout **Purpose:** Terminates the current session and clears associated authentication tokens. #### Behavior * Invalidates the session (if it exists). * Clears cookie `projectname-access-token[-tenantCodename]`. * Returns a confirmation response (always `200 OK`). #### Example ```js axios.post("/logout", {}, { headers: { "Authorization": "Bearer your-jwt-token" } }); ``` #### Notes * Can be called without a session (idempotent behavior). * Works for both cookie-based and token-based sessions. #### Success Response ```json { "status": "OK", "message": "User logged out successfully" } ``` ### `GET /currentuser` — Current Session **Purpose** Returns the currently authenticated user's session. **Route Type** `sessionInfo` **Authentication** Requires a valid access token (header or cookie). #### Request *No parameters.* #### Example ```js axios.get("/currentuser", { headers: { Authorization: "Bearer " } }); ``` #### Success (200) Returns the session object (identity, tenancy, token metadata): ```json { "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9", "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "tenantId": "abc123", "accessToken": "jwt-token-string", "...": "..." } ``` Note that the `currentuser` API returns a session object, so there is no `id` property, instead, the values for the user and session are exposed as `userId` and `sessionId`. The response is a mix of user and session information. #### Errors * **401 Unauthorized** — No active session/token ```json { "status": "ERR", "message": "No login found" } ``` **Notes** * Commonly called by web/mobile clients after login to hydrate session state. * Includes key identity/tenant fields and a token reference (if applicable). * Ensure a valid token is supplied to receive a 200 response. After you complete this step, please ensure you have not made the following common mistakes: 1. The `/currentuser` API returns a mix of session and user data. There is no `id` property —use `userId` and `sessionId`. 2. Note that any API call to the auth service should use the `/auth-api` prefix after the application's base URL. **After this prompt, the user may give you new instructions to update your output or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Verification Management** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document includes the verification processes for the autheitcation flow. Please read it carefully and implement all requirements described here. The project has 1 auth service, 1 notification service, 1 BFF service, and 4 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service. Each service is a separate microservice application and listens for HTTP requests at different service URLs. Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page. ## Accessing the backend Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services. For the auth service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/auth-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/auth-api` * **Production:** `https://auteurlabb.mindbricks.co/auth-api` Any request that requires login must include a valid token in the Bearer authorization header. ## After User Registration Frontend should also be aware of verification after any login attempt. The login request may return a 401 or 403 with the error codes that indicates the verification needs. ```json { //... "errCode": "EmailVerificationNeeded", // or "errCode": "MobileVerificationNeeded", } ``` ## Email Verification In the registration response, check the `emailVerificationNeeded` property in the response root. If it is `true`, start the email verification flow. After the login process, if you receive an HTTP error and the response contains an `errCode` with the value `EmailVerificationNeeded`, start the email verification flow. 1. Call the email verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the provided email address. **The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the `secretCode` property of the response.** 2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. **If the `secretCode` is sent to the frontend for testing, display it on the input page so the user can copy and paste it.** 3. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index in the message with the one on the screen. 4. When the user submits the code, complete the email verification using the `complete` route of the backend (described below) with the user's email and the secret code. 5. After a successful email verification response, please check the response object to have the property 'mobileVerificationNeeded' as `true`, if so navigate to the mobile verification flow as described below. **If no mobile verification is needed then just navigate the login page.** Below are the `start` and `complete` routes for email verification. These are system routes and therefore are not versioned. #### `POST /verification-services/email-verification/start` **Purpose:** Starts email verification by generating and sending a secret code. | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------ | | `email` | String | Yes | User's email address to verify | **Example Request** ```json { "email": "user@example.com" } ``` **Success Response** ```json { "status": "OK", "codeIndex": 1, // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)", // expireTime: in seconds "expireTime": 86400, "verificationType": "byLink", // in testMode "secretCode": "123456", "userId": "user-uuid" } ``` > ⚠️ In production, `secretCode` is **not** returned — it is only sent via email. **Error Responses** * `400 Bad Request`: Already verified * `403 Forbidden`: Too many attempts (rate limit) --- #### `POST /verification-services/email-verification/complete` **Purpose:** Completes verification using the received code. | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ----------------- | | `email` | String | Yes | User's email | | `secretCode` | String | Yes | Verification code | **Success Response** ```json { "status": "OK", "isVerified": true, "email": "user@email.com", // in testMode "userId": "user-uuid" } ``` **Error Responses** * `403 Forbidden`: Code expired or mismatched * `404 Not Found`: No verification in progress --- ## Mobile Verification > **Mobile numbers must be in E.164 format** (`+` followed by country code and subscriber number, e.g. `+905551234567`). Use the `PhoneInput` component for mobile number inputs on verification pages. In the registration response, check the `mobileVerificationNeeded` property in the response root. If it is `true`, start the mobile verification flow. After the login process, if you receive a 403 error and the response contains an `errCode` with the value `MobileVerificationNeeded`, start the mobile verification flow. 1. Call the mobile verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the user's mobile number. **If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the `secretCode` property.** 2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. **If the `secretCode` is returned for testing, display it on the input page for easy copy/paste.** 3. When the user submits the code, complete mobile verification using the `complete` route of the backend (described below) with the user's email and the secret code. 4. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index shown in the message with the one on the screen. 5. After a successful mobile verification response, navigate to the login page. **Verification Order** If both `emailVerificationNeeded` and `mobileVerificationNeeded` are `true`, handle both verification flows in order. First complete email verification, then mobile verification. Below are the `start` and `complete` routes for mobile verification. These are system routes and therefore are not versioned. #### `POST /verification-services/mobile-verification/start` | Parameter | Type | Required | Description | | --------- | ------ | -------- | ------------------------------------ | | `email` | String | Yes | User's email to locate mobile record | **Success Response** ```json { "status": "OK", "codeIndex": 1, // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)", // expireTime: in seconds "expireTime": 180, "verificationType": "byCode", // in testMode "secretCode": "123456", "userId": "user-uuid" } ``` > ⚠️ `secretCode` is returned only in development. **Errors** * `400 Bad Request`: Already verified * `403 Forbidden`: Rate-limited --- #### `POST /verification-services/mobile-verification/complete` | Parameter | Type | Required | Description | | ------------ | ------ | -------- | --------------------- | | `email` | String | Yes | Associated email | | `secretCode` | String | Yes | Code received via SMS | **Success Response** ```json { "status": "OK", "isVerified": true, "mobile": "+1 333 ...", // in testMode "userId": "user-uuid" } ``` --- ## Resetting Password Users can reset their forgotten passwords without a login required, through email and mobile verification. To be able to start a password reset flow, users will click on the "Reset Password" link in the login page. Since there are two verification methods, by email or by mobile, for password reset, when the reset password link is clicked, frontend should ask user if they want to make the verification through email of mobile. According to the users selection the frontend shoudl start the related flow as explaned below step by step. ## Password Reset By Email Flow 1. Call the password reset by email verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the provided email address. **The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the `secretCode` property of the response.** 2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. **If the `secretCode` is sent to the frontend for testing, display it on the input page so the user can copy and paste it.** 3. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index in the message with the one on the screen. 4. The input page should also include a double input area for the user to enter and confirm their new password. 5. When the user submits the code and the new password, complete the password reset by email using the `complete` route of the backend (described below) with the user's email , the secret code and new password. 6. After a successful verification response, navigate to the login page. Below are the `start` and `complete` routes for password reset by email verification. These are system routes and therefore are not versioned. #### POST `/verification-services/password-reset-by-email/start` **Purpose**: Starts the password reset process by generating and sending a secret verification code. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|-------------------------------------| | email | String | Yes | The email address of the user | ```json { "email": "user@example.com" } ``` **Success Response** Returns secret code details (only in development environment) and confirmation that the verification step has been started. ```json { "userId": "user-uuid", "email": "user@example.com", "codeIndex": 1, "secretCode": "123456", "timeStamp": 1765484354, "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z", "verificationType": "byLink", } ``` ⚠️ In production, the secret code is only sent via email and not exposed in the API response. **Error Responses** - `401 NotAuthenticated`: Email address not found or not associated with a user. - `403 Forbidden`: Sending a code too frequently (spam prevention). --- #### POST `/verification-services/password-reset-by-email/complete` **Purpose**: Completes the password reset process by validating the secret code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|----------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via email | | password | String | Yes | The new password the user wants to set | ```json { "email": "user@example.com", "secretCode": "123456", "password": "newSecurePassword123" } ``` **Success Response** ```json { "userId": "user-uuid", "email": "user@example.com", "isVerified": true } ``` **Error Responses** - `403 Forbidden`: - Secret code mismatch - Secret code expired - No ongoing verification found --- ## Password Reset By Mobile Flow 1. Call the password reset by mobile verification `start` route of the backend (described below) with the user's email. The backend will send a secret code to the user's mobile number. **If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the `secretCode` property.** 2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. **If the `secretCode` is returned for testing, display it on the input page for easy copy/paste.** 3. The `start` response includes a `codeIndex` property. Display its value on the input page so the user can match the index in the message with the one on the screen. Also display the half masked `mobile`number that comes in the response, to tell the user that their code is sent to this number. 4. The input page should also include a double input area for the user to enter and confirm their new password. 5. When the user submits the code, complete mobile verification using the `complete` route of the backend (described below) with the user's email and the secret code. 6. After a successful mobile verification response, navigate to the login page. Below are the `start` and `complete` routes for password reset by mobile verification. These are system routes and therefore are not versioned. #### POST `/verification-services/password-reset-by-mobile/start` **Purpose**: Initiates the mobile-based password reset by sending a verification code to the user's mobile. #### Request Body | Parameter | Type | Required | Description | |-----------|--------|----------|------------------------------| | email | String | Yes | The email of the user that resets the password | ```json { "email": "user@user.com" } ``` ### Success Response Returns the verification context (code returned only in development): ```json { "status": "OK", "codeIndex": 1, timeStamp: 133241255, "mobile": "+905.....67", "secretCode": "123456", "expireTime": 86400, "date": "2024-04-29T10:00:00.000Z", verificationType: "byLink" } ``` ⚠️ In production, the `secretCode` is not included in the response and is only sent via SMS. ### Error Responses - **400 Bad Request**: Mobile already verified - **403 Forbidden**: Rate-limited (code already sent recently) - **404 Not Found**: User with provided mobile not found --- #### POST `/verification-services/password-reset-by-mobile/complete` **Purpose**: Finalizes the password reset process by validating the received verification code and updating the user's password. #### Request Body | Parameter | Type | Required | Description | |-------------|--------|----------|-------------------------------------------------| | email | String | Yes | The email address of the user | | secretCode | String | Yes | The code received via SMS | | password | String | Yes | The new password to assign | ```json { "email": "user@example.com", "secretCode": "123456", "password": "NewSecurePassword123!" } ``` ### Success Response ```json { "userId": "user-uuid", "isVerified": true } ``` --- ## Two-Factor Authentication (2FA) **This project has email and mobile two-factor authentication enabled.** 2FA is different from email/mobile verification: verification proves ownership during registration (one-time), while **2FA runs on every login** as an additional security layer. ### How 2FA Works After Login When a user logs in successfully, the login response includes `accessToken`, `userId`, `sessionId`, and all session data. However, when 2FA is active, the response **also** contains one or both of these flags: * `sessionNeedsEmail2FA: true` — email 2FA is required * `sessionNeedsMobile2FA: true` — mobile 2FA is required **When any of these flags are `true`, the session is NOT fully authorized.** The `accessToken` is valid only for calling the 2FA verification endpoints. All other protected API calls will return `403 Forbidden` with error code `EmailTwoFactorNeeded` or `MobileTwoFactorNeeded` until 2FA is completed. ### 2FA Frontend Flow 1. After a successful login, check the response for `sessionNeedsEmail2FA` or `sessionNeedsMobile2FA`. 2. If either is `true`, **do not treat the user as authenticated**. Store the `accessToken`, `userId`, and `sessionId` temporarily. 3. Navigate the user to a **2FA verification page**. 4. On the 2FA page, immediately call the 2FA `start` endpoint (described below) with the `userId` and `sessionId`. This triggers sending the verification code to the user's email or mobile. 5. Display a 6-digit code input. **If the response contains `secretCode` (test/development mode), display it on the page so the user can copy and paste it.** 6. The `start` response includes a `codeIndex` property. Display its value on the page so the user can match the index in the message with the one on the screen. 7. When the user submits the code, call the 2FA `complete` endpoint with `userId`, `sessionId`, and `secretCode`. 8. On success, the `complete` endpoint returns the **updated session object** with the 2FA flag cleared. Now set the user as fully authenticated and navigate to the main application page. 9. Provide a "Resend Code" button with a **60-second cooldown** to prevent spam. 10. Provide a "Cancel" option that discards the partial session and returns the user to the login page. ### 2FA Type Selection When both email and mobile 2FA are enabled, the login response may have both `sessionNeedsEmail2FA: true` and `sessionNeedsMobile2FA: true`. In this case, handle email 2FA first, then mobile 2FA — similar to the verification order for email and mobile verification. ### Email 2FA Endpoints #### `POST /verification-services/email-2factor-verification/start` **Purpose:** Starts email-based 2FA by generating and sending a verification code to the user's email. | Parameter | Type | Required | Description | | ----------- | ------ | -------- | ------------------------------ | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The current session ID | **Example Request** ```json { "userId": "user-uuid", "sessionId": "session-uuid" } ``` **Success Response** ```json { "status": "OK", "sessionId": "session-uuid", "userId": "user-uuid", "codeIndex": 1, "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300", "expireTime": 86400, "verificationType": "byCode", // in testMode only "secretCode": "123456" } ``` > ⚠️ In production, `secretCode` is **not** returned — it is only sent via email. **Error Responses** * `403 Forbidden`: Code resend attempted before cooldown (60s) * `401 Unauthorized`: Session not found --- #### `POST /verification-services/email-2factor-verification/complete` **Purpose:** Completes email 2FA by validating the code and clearing the session 2FA flag. | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ----------------------------- | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The session ID | | `secretCode` | String | Yes | Verification code from email | **Success Response** Returns the updated session with `sessionNeedsEmail2FA: false`: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "email": "user@example.com", "fullname": "John Doe", "roleId": "user", "sessionNeedsEmail2FA": false, "accessToken": "jwt-token", "...": "..." } ``` **Error Responses** * `403 Forbidden`: Code mismatch or expired * `403 Forbidden`: No ongoing verification found * `401 Unauthorized`: Session does not exist --- ### Mobile 2FA Endpoints > **Important:** Mobile 2FA requires that the user has a **verified mobile number**. If the user's mobile is not verified, the start endpoint will return a `403` error. #### `POST /verification-services/mobile-2factor-verification/start` **Purpose:** Starts mobile-based 2FA by generating and sending a verification code via SMS. | Parameter | Type | Required | Description | | ----------- | ------ | -------- | ------------------------------ | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The current session ID | **Example Request** ```json { "userId": "user-uuid", "sessionId": "session-uuid" } ``` **Success Response** ```json { "status": "OK", "sessionId": "session-uuid", "userId": "user-uuid", "codeIndex": 1, "timeStamp": 1784578660000, "date": "Mon Jul 20 2026 23:17:40 GMT+0300", "expireTime": 300, "verificationType": "byCode", // in testMode only "secretCode": "654321" } ``` > ⚠️ In production, `secretCode` is **not** returned — it is only sent via SMS. **Error Responses** * `403 Forbidden`: Mobile number not verified * `403 Forbidden`: Code resend attempted before cooldown (60s) * `401 Unauthorized`: Session not found --- #### `POST /verification-services/mobile-2factor-verification/complete` **Purpose:** Completes mobile 2FA by validating the code and clearing the session 2FA flag. | Parameter | Type | Required | Description | | ------------ | ------ | -------- | ---------------------------- | | `userId` | String | Yes | The user's ID | | `sessionId` | String | Yes | The session ID | | `secretCode` | String | Yes | Code received via SMS | **Success Response** Returns the updated session with `sessionNeedsMobile2FA: false`: ```json { "sessionId": "session-uuid", "userId": "user-uuid", "mobile": "+15551234567", "fullname": "John Doe", "roleId": "user", "sessionNeedsMobile2FA": false, "accessToken": "jwt-token", "...": "..." } ``` **Error Responses** * `403 Forbidden`: Code mismatch or expired * `403 Forbidden`: No ongoing verification found * `401 Unauthorized`: Session does not exist --- ### Important 2FA Notes * **One code per session**: Only one active verification code exists per session at a time. * **Resend throttling**: Code requests are throttled — wait at least 60 seconds between resend attempts. * **Code expiration**: Codes expire after 86400 seconds. * **Session stays valid**: The `accessToken` from login remains the same throughout the 2FA flow — you do not get a new token. The `complete` response returns the same session with the 2FA flag cleared. * **`/currentuser` works during 2FA**: The `/currentuser` endpoint does **not** enforce 2FA, so it can be called during the 2FA flow. However, all other protected endpoints will return `403`. ** Please dont forget to arrange the code to be able to navigate to the verification pages both after registrations and login attempts if verification is needed.** **After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - Profile Management** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document includes information and api descriptions about building a **profile page** in the frontend using the auth service profile api calls. Avatar images are stored in the auth service's database buckets — no external bucket service is needed for avatars. The project has 1 auth service, 1 notification service, 1 BFF service, and 4 business services, plus other helper services such as bucket and realtime. In this document you will use the auth service (including its database bucket endpoints for avatar uploads). Each service is a separate microservice application and listens for HTTP requests at different service URLs. Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page. ## Accessing the backend Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the register and login pages include a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services. The base URL of the application in each environment is as follows: * **Preview:** `https://auteurlabb.prw.mindbricks.com` * **Staging:** `https://auteurlabb-stage.mindbricks.co` * **Production:** `https://auteurlabb.mindbricks.co` For the auth service, service urls are as follows: * **Preview:** `https://auteurlabb.prw.mindbricks.com/auth-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/auth-api` * **Production:** `https://auteurlabb.mindbricks.co/auth-api` For each other service, the service URL will be given in the service sections. Any request that requires login must include a valid token in the Bearer authorization header. ## Avatar Storage (Database Buckets) User avatars and tenant avatars are stored directly in the auth service database using **database buckets** (dbBuckets). This means avatar files are uploaded to and downloaded from the **auth service itself** — no external bucket service is needed. The auth service provides these avatar buckets: ### User Avatar Bucket **Upload:** `POST {authBaseUrl}/bucket/userAvatars/upload` **Download by ID:** `GET {authBaseUrl}/bucket/userAvatars/download/{fileId}` **Download by Key:** `GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}` - **Read access:** Public (anyone can view avatars, no auth needed for download) - **Write access:** Authenticated (any logged-in user can upload their own avatar) - **Allowed types:** image/png, image/jpeg, image/webp, image/gif - **Max size:** 5 MB - **Access key:** Each uploaded file gets a 12-character random key for shareable links **Upload example (multipart/form-data):** ```js const formData = new FormData(); formData.append('file', croppedImageBlob, 'avatar.png'); const response = await fetch(`${authBaseUrl}/bucket/userAvatars/upload`, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}`, }, body: formData, }); const result = await response.json(); // result.file.id — the file ID (use for download URL) // result.file.accessKey — 12-char key for public sharing // result.file.fileName, result.file.mimeType, result.file.fileSize ``` **After uploading, update the user's avatar field** with the download URL: ```js const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/${result.file.id}`; // OR use the access key for a shorter, shareable URL: const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`; await updateProfile({ avatar: avatarUrl }); ``` **Displaying avatars:** Since read access is public, avatar URLs can be used directly in `` tags without any authentication token: ```jsx Avatar ``` ### Listing and Deleting Avatars The auth service also provides metadata APIs for each bucket (auto-generated): | API | Method | Path | Description | |-----|--------|------|-------------| | `getUserAvatarsFile` | GET | `/v1/userAvatarsFiles/:id` | Get file metadata (no binary) | | `listUserAvatarsFiles` | GET | `/v1/userAvatarsFiles` | List files with filtering | | `deleteUserAvatarsFile` | DELETE | `/v1/userAvatarsFiles/:id` | Delete file and its data | ## Profile Page Design a profile page to manage (view and edit) user information. The profile page should include an avatar upload component that uploads to the database bucket. On the profile page, you will need 4 business APIs: `getUser` , `updateProfile`, `updateUserPassword` and `archiveProfile`. Do not rely on the `/currentuser` response for profile data, because it contains session information. The most recent user data is in the user database and should be accessed via the `getUser` business API. The `updateProfile`, `updateUserPassword` and `archiveProfile` api can only be called by the users themselves. They are designed specific to the profile page. **Avatar upload workflow:** 1. User selects an image → crop with `react-easy-crop` (install it, do not implement your own) 2. Convert cropped area to a Blob 3. Upload to `POST {authBaseUrl}/bucket/userAvatars/upload` with the access token 4. Get back the file metadata (id, accessKey) 5. Construct the download URL: `{authBaseUrl}/bucket/userAvatars/download/key/{accessKey}` 6. Call `updateProfile({ avatar: downloadUrl })` to save it **Note that the user cannot change/update their `email` or `roleId`.** For password update you should make a separate block in the UI, so that user can enter old password, new password and confirm new password before calling the `updateUserPassword`. Here are the 3 auth APIs—`getUser` , `updateProfile` and `updateUserPassword`— as follows: You can access these APIs through the auth service base URL, `{appUrl}/auth-api`. ### `Get User` API This api is used by admin roles or the users themselves to get the user profile information. **Rest Route** The `getUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `getUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users/:userId** ```js axios({ method: 'GET', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "approvalStatus": "Enum", "approvalStatus_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 4 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"] | | approvalStatus | Enum | false | request.body?.["approvalStatus"] | **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 **approvalStatus** : Admin approval status for the user account (pending, approved, rejected). **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", approvalStatus:"Enum", }, 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", "approvalStatus": "Enum", "approvalStatus_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", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Archiving A Profile A user may want to archive their profile. So the profile page should include an archive section for the users to archive their accounts. When an account is archived, it is marked as archived and an aarchiveDate is atteched to the profile. All user data is kept in the database for 1 month after user archived. If user tries to login or register with the same email, the account will be activated again. But if no login or register occures in 1 month after archiving, the profile and its related data will be deleted permanenetly. So in the profile page, 1. The arcihve options should be accepted after user writes a text like ("ARCHİVE MY ACCOUNT") to a confirmation dialog, so that frontend UX can ensure this is not an unconscious request. 2. The user should be warned about the process, that his account will be available for a restore for 1 month. The archive api, can only be called by the users themselves and its used as follows. ### `Archive Profile` API This api is used by users to archive their profiles. **Rest Route** The `archiveProfile` API REST controller can be triggered via the following route: `/v1/archiveprofile/:userId` **Rest Request Parameters** The `archiveProfile` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/archiveprofile/:userId** ```js axios({ method: 'DELETE', url: `/v1/archiveprofile/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- After you complete this step, please ensure you have not made the following common mistakes: 1. Avatar uploads go to the **auth service's database bucket** endpoints (`/bucket/userAvatars/upload`), not to an external bucket service. Use the same `accessToken` (Bearer header) for both auth APIs and avatar bucket uploads — no bucket-specific tokens are needed. 2. Note that any api call to the application backend is based on a service base url, in this prompt all auth apis (including avatar bucket endpoints) should be called by the auth service base url. 3. On the profile page, fetch the latest user data from the service using `getUser`. The `/currentuser` API is session-stored data; the latest data is in the database. 4. When you upload the avatar image on the profile page, use the returned download URL as the user's `avatar` property and update the user record when the Save button is clicked. **After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - User Management** This document is the 2nd part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document provides extensive instruction for administrative user management. ## Service Access User management is handled through auth service again. Auth service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the auth service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/auth-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/auth-api` * **Production:** `https://auteurlabb.mindbricks.co/auth-api` Please note that any feature in this document is open to admins only. When the user logins, the response includes a roleId field. This roleId should one of these following admin roles. `superAdmin`, `admin`, ## Scope Auth service provides following feature for user management in auteurlabb application. These features are already handled in the previous part. 1. User Registration 2. User Authentication 3. Password Reset 3. Email (and/or) Mobile Verification 4. Profile Management These features will be handled in this part. - User Management - User Groups Management - Permission Manageemnt ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API's response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## User Management User management will be one of the main parts of the administrative manageemnts, so there will be a minimal but fancy `users` page in the admin dashboard. ### User Roles - `superadmin` : The first creator of the backend, the owner of the application, root user, has got an absolute authroization on all actions. It can not be assgined any other user. It can't be unassigned. Super admin user can not be deleted in any way. - `admin` : The role that can be assigned to any user by the super admin. This role includes most permissions that super admin have, but admins can't assign admin roles, can't unassign an admin role, can't delete other users who have admin role. In addition to these limitations, some critical actions in the business services may also be open to only super admin. - `user` : The standard role that is assgined to every user when first created or registered. This role doesnt have any privilages and can access to their own data or public data. Along with the default roles, this project also configured to have the following roles: `filmmaker` `studio` `investor` `normalUser` The roles object is a hardcoded object in the generated code, and it contains the following roles: ```json { "superAdmin": "'superAdmin'", "admin": "'admin'", "user": "'user'", "filmmaker": "'filmmaker'", "studio": "'studio'", "investor": "'investor'", "normalUser": "'normalUser'" } ``` Each user may have only one role, and it is given in `/login` , `/currentuser` or `/users/:userId` response as follows ```json { // ... "roleId":"superAdmin", // ... } ``` ## Listing Users You can list users using the `listUsers` api. ### `List Users` API The list of users is filtered by the tenantId. **Rest Route** The `listUsers` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** **Filter Parameters** The `listUsers` api supports 3 optional filter parameters for filtering list results: **email** (`String`): A string value to represent the user's email. - Single (partial match, case-insensitive): `?email=` - Multiple: `?email=&email=` - Null: `?email=null` **fullname** (`String`): A string value to represent the fullname of the user - Single (partial match, case-insensitive): `?fullname=` - Multiple: `?fullname=&fullname=` - Null: `?fullname=null` **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/users** ```js axios({ method: 'GET', url: '/v1/users', data: { }, params: { // Filter parameters (see Filter Parameters section above) // email: '' // Filter by email // fullname: '' // Filter by fullname // roleId: '' // Filter by roleId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ## Searching Users You may search users with their full names, emails. The search is done in elasticsearch index of the user table so a fast response is provided by the backend. You can send search request on each character update in the search box but start searching after 3 chars. The keyword parameter that is used in the business logic of the api, is read from the keyword query parameter. eg: `GET /v1/searchusers?keyword=Joe` When the user deletes the search keyword, use the `listUsers` api to get the full list again. ### `Search Users` API The list of users is filtered by the tenantId. **Rest Route** The `searchUsers` API REST controller can be triggered via the following route: `/v1/searchusers` **Rest Request Parameters** The `searchUsers` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | keyword | String | true | request.query?.["keyword"] | **keyword** : **Filter Parameters** The `searchUsers` api supports 1 optional filter parameter for filtering list results: **roleId** (`String`): A string value to represent the roleId of the user. - Single (partial match, case-insensitive): `?roleId=` - Multiple: `?roleId=&roleId=` - Null: `?roleId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/searchusers** ```js axios({ method: 'GET', url: '/v1/searchusers', data: { }, params: { keyword:'"String"', // Filter parameters (see Filter Parameters section above) // roleId: '' // Filter by roleId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "users", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "users": [ { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` #### Pagination When you list the users please use pagination. To be able to use pagination you should provide a `pageNumber` paramater in the query. The default row count for one page is 25, add an option for user to change it to 50 or 100. You can provide this value to the api through the `pageRowCount` parameter; `GET /users?pageNumber=1&pageRowCount=50` ## Creating Users The user management console in the admin dashboard should provide UX components for user creating by admins. When creating users, it should also be possible to upload user avatar. Note that when creating, updating users, admins can not set emailVerified as true, since it is a logical mechanism and should be verified only through verification processes. ### `Create User` API This api is used by admin roles to create a new user manually from admin panels **Rest Route** The `createUser` API REST controller can be triggered via the following route: `/v1/users` **Rest Request Parameters** The `createUser` api has got 4 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"] | **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 **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", }, 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", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Avatar Upload Avatars are stored in the auth service's **database bucket** — no external bucket service needed. Upload the avatar image to the auth service's userAvatars bucket endpoint: `POST {authBaseUrl}/bucket/userAvatars/upload` Use the regular access token (Bearer header) for authentication — the same token used for all other API calls. The upload body is `multipart/form-data` with a `file` field. After upload, the response returns file metadata including `id` and `accessKey`. Construct a public download URL and save it in the user's `avatar` field: ```js const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`; await updateUser(userId, { avatar: avatarUrl }); ``` Since the userAvatars bucket has public read access, avatar URLs work directly in `` tags without auth. Before the avatar upload, use the `react-easy-crop` lib for zoom, pan and crop. This component is also used in the profile page — reuse the existing code. ## Updating Users User update is possible by `updateUser`api. However since this update api is also called by teh user themselves it is lmited with name and avatar change (or any other user related property). For roleId and password updates seperate apis are used. So arrange the user update UI as to update the user info, as to set roleId and as to update password. ### `Update User` API This route is used by admins to update user profiles. **Rest Route** The `updateUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `updateUser` api has got 4 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"] | | approvalStatus | Enum | false | request.body?.["approvalStatus"] | **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 **approvalStatus** : Admin approval status for the user account (pending, approved, rejected). **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", approvalStatus:"Enum", }, 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", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` For role updates there are some rules. 1. Superadmin role can not be unassigned even by superadmin. 2. Admin roles can be assgined or unassgined only by superadmin. 3. All other roles can be assigned and unassgined by admins and superadmin. For password updates there are some rules. 1. Superadmin and admin passwords can be updated only by superadmin. 2. Admins can update only non-admin passwords. ### `Update Userrole` API This route is used by admin roles to update the user role.The default role is user when a user is registered. A user's role can be updated by superAdmin or admin **Rest Route** The `updateUserRole` API REST controller can be triggered via the following route: `/v1/userrole/:userId` **Rest Request Parameters** The `updateUserRole` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | | roleId | String | true | request.body?.["roleId"] | **userId** : This id paremeter is used to select the required data object that will be updated **roleId** : The new roleId of the user to be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/userrole/:userId** ```js axios({ method: 'PATCH', url: `/v1/userrole/${userId}`, data: { roleId:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "approvalStatus": "Enum", "approvalStatus_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", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### Deleting Users Deleting users is possible in certain conditions. 1. SuperAdmin can not be deleted. 2. Admins can be deleted by only superadmin. 3. Users can be deleted by admins or superadmin. ### `Delete User` API This api is used by admins to delete user profiles. **Rest Route** The `deleteUser` API REST controller can be triggered via the following route: `/v1/users/:userId` **Rest Request Parameters** The `deleteUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.params?.["userId"] | **userId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/users/:userId** ```js axios({ method: 'DELETE', url: `/v1/users/${userId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "user", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "user": { "id": "ID", "email": "String", "password": "String", "fullname": "String", "avatar": "String", "roleId": "String", "emailVerified": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` --- When you list user group members, a `user` object will also be inserted in each userGroupMember object, with fullname, avatar, email. ## Avatar Storage (Database Buckets) (This information is also covered in the Profile prompt.) Avatars are stored in the auth service's **database buckets** — uploaded to and downloaded from the auth service directly using the regular access token. **User Avatar Bucket:** - Upload: `POST {authBaseUrl}/bucket/userAvatars/upload` (multipart/form-data, `file` field) - Download: `GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}` (public, no auth needed) - Allowed: image/png, image/jpeg, image/webp, image/gif (max 5 MB) When uploading an avatar (for user creation or update), send the image to the bucket, get back the `accessKey`, construct the download URL, and store it in the user's `avatar` field via the update API. **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - MCP BFF Integration** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project's backend. This document provides comprehensive instructions for integrating the **MCP BFF** (Model Context Protocol - Backend for Frontend) service into the frontend application. The MCP BFF is the central gateway between the frontend AI chat and all backend services. --- ## MCP BFF Architecture Overview The Auteurlabb application uses an **MCP BFF** service that aggregates multiple backend MCP servers into a single frontend-facing API. Instead of the frontend connecting to each service's MCP endpoint directly, it communicates exclusively through the MCP BFF. ``` ┌────────────┐ ┌───────────┐ ┌─────────────────┐ │ Frontend │────▶│ MCP BFF │────▶│ Auth Service │ │ (Chat UI) │ │ :3005 │────▶│ Business Svc 1 │ │ │◀────│ │────▶│ Business Svc N │ └────────────┘ SSE └───────────┘ └─────────────────┘ ``` ### Key Responsibilities - **Tool Aggregation**: Discovers and registers tools from all connected MCP services - **Session Forwarding**: Injects the user's `accessToken` into every MCP tool call - **AI Orchestration**: Routes user messages to the AI model, which decides which tools to call - **SSE Streaming**: Streams chat responses, tool executions, and results to the frontend in real-time - **Elasticsearch**: Provides direct search/aggregation endpoints across all project indices - **Logging**: Provides log viewing and real-time console streaming endpoints ## MCP BFF Service URLs For the MCP BFF service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/mcpbff-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/mcpbff-api` * **Production:** `https://auteurlabb.mindbricks.co/mcpbff-api` All endpoints below are relative to the MCP BFF base URL. --- ## Authentication All MCP BFF endpoints require authentication. The user's access token (obtained from the Auth service login) must be included in every request: ```js const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}`, }; ``` --- ## Chat API (AI Interaction) The chat API is the primary interface for AI-powered conversations. It supports both regular HTTP responses and **SSE streaming** for real-time output. ### POST /api/chat — Regular Chat Send a message and receive the complete AI response. ```js const response = await fetch(`${mcpBffUrl}/api/chat`, { method: 'POST', headers, body: JSON.stringify({ message: "Show me all orders from last week", conversationId: "optional-conversation-id", // for conversation context context: {} // additional context }), }); ``` ### POST /api/chat/stream — SSE Streaming Chat (Recommended) Stream the AI response in real-time using Server-Sent Events (SSE). This is the recommended approach for chat UIs as it provides immediate feedback while the AI is thinking, calling tools, and generating text. **Request:** ```js const response = await fetch(`${mcpBffUrl}/api/chat/stream`, { method: 'POST', headers, body: JSON.stringify({ message: "Create a new product called Widget", conversationId: conversationId, // optional, auto-generated if omitted disabledServices: [], // optional, service names to exclude }), }); ``` **Response:** The server responds with `Content-Type: text/event-stream`. Each SSE frame follows the standard format: ``` event: \n data: \n \n ``` ### SSE Event Types The streaming endpoint emits the following event types in order: | Event | When | Data Shape | |-------|------|------------| | `start` | First event, once per stream | `{ conversationId, provider, aliasMapSummary }` | | `text` | AI text token streamed (many per response) | `{ content }` | | `tool_start` | AI decided to call a tool | `{ tool }` | | `tool_executing` | Tool invocation started with resolved args | `{ tool, args }` | | `tool_result` | Tool execution completed | `{ tool, result, success, error? }` — **check for `__frontendAction`** | | `error` | Unrecoverable error | `{ message }` | | `done` | Last event, once per stream | `{ conversationId, toolCalls, processingTime, aliasMapSummary }` | ### SSE Event Data Reference **`start`** — Always the first event. Use `conversationId` for subsequent requests in the same conversation. ```json { "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453", "provider": "anthropic", "aliasMapSummary": { "enabled": true, "count": 0, "samples": [] } } ``` **`text`** — Streamed token-by-token as the AI generates its response. Concatenate `content` fields to build the full markdown message. ```json { "content": "Here" } { "content": "'s your" } { "content": " current session info" } ``` **`tool_start`** — The AI decided to call a tool. Use this to show a loading/spinner UI for the tool. ```json { "tool": "currentuser" } ``` **`tool_executing`** — Tool is now executing with these arguments. Use this to display what the tool is doing. ```json { "tool": "currentuser", "args": { "organizationCodename": "babil" } } ``` **`tool_result`** — Tool finished. Check `success` to determine if it succeeded. The `result` field contains the MCP tool response envelope. ```json { "tool": "currentuser", "result": { "success": true, "service": "auth", "tool": "currentuser", "result": { "content": [{ "type": "text", "text": "{...JSON...}" }] } }, "success": true } ``` On failure, `success` is `false` and an `error` string is present: ```json { "tool": "listProducts", "error": "Connection refused", "success": false } ``` **`done`** — Always the last event. Contains a summary of all tool calls made and total processing time in milliseconds. ```json { "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453", "toolCalls": [ { "tool": "currentuser", "result": { "success": true, "..." : "..." } } ], "processingTime": 10026, "aliasMapSummary": { "enabled": true, "count": 6, "samples": [{ "alias": "user_admin_admin_com" }, { "alias": "tenant_admin_admin_com" }] } } ``` **`error`** — Sent when an unrecoverable error occurs (e.g., AI service unavailable). The stream ends after this event. ```json { "message": "AI service not configured. Please configure OPENAI_API_KEY or ANTHROPIC_API_KEY in environment variables" } ``` ### SSE Event Lifecycle A typical conversation stream follows this lifecycle: ``` start ├── text (repeated) ← AI's initial text tokens ├── tool_start ← AI decides to call a tool ├── tool_executing ← tool running with resolved args ├── tool_result ← tool finished ├── text (repeated) ← AI continues writing after tool result ├── tool_start → tool_executing → tool_result ← may repeat ├── text (repeated) ← AI's final text tokens done ``` Multiple tool calls can happen in a single stream. The AI interleaves text and tool calls — text before tools (explanation), tools in the middle (data retrieval), and text after tools (formatted response using the tool results). ### Inline Segment Rendering (Critical UX Pattern) **Tool cards MUST be rendered inline inside the assistant message bubble, at the exact position where they occur in the stream — not grouped at the top, not grouped at the bottom, and not outside the bubble.** The assistant message is an ordered list of **segments**: text segments and tool segments, interleaved in the order they arrive. Each segment appears inside the same message bubble, in sequence: ``` ┌─────────────────────────────────────────────────┐ │ [Rendered Markdown — text before tool call] │ │ │ │ ┌─ Tool Card ─────────────────────────────────┐ │ │ │ 🔧 currentuser ✓ success │ │ │ │ args: { organizationCodename: "babil" } │ │ │ └─────────────────────────────────────────────┘ │ │ │ │ [Rendered Markdown — text after tool call] │ │ │ │ ┌─ Tool Card ─────────────────────────────────┐ │ │ │ 🔧 listProducts ✓ success │ │ │ └─────────────────────────────────────────────┘ │ │ │ │ [Rendered Markdown — final text] │ └─────────────────────────────────────────────────┘ ``` To achieve this, maintain an **ordered segments array**. Each segment is either `{ type: 'text', content: string }` or `{ type: 'tool', ... }`. When SSE events arrive: 1. **`text`** — Append to the last segment if it is a text segment; otherwise push a new text segment. 2. **`tool_start`** — Push a new tool segment (status: `running`). This "cuts" the current text segment — any further `text` events after the tool completes will start a new text segment. 3. **`tool_executing`** — Update the current tool segment with `args`. 4. **`tool_result`** — Update the current tool segment with `result`, `success`, `error`. Check for `__frontendAction`. 5. After `tool_result`, the next `text` event creates a **new** text segment (the AI is now responding after reviewing the tool result). Render the message bubble by mapping over the segments array in order, rendering each text segment as markdown and each tool segment as a collapsible tool card. ### Parsing SSE Events (Frontend Implementation) Use the `fetch` API with a streaming reader. SSE frames can arrive split across chunks, so buffer partial lines: ```js async function streamChat(mcpBffUrl, headers, message, conversationId, onEvent) { const response = await fetch(`${mcpBffUrl}/api/chat/stream`, { method: 'POST', headers, body: JSON.stringify({ message, conversationId }), }); const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const parts = buffer.split('\n\n'); buffer = parts.pop(); // keep incomplete frame in buffer for (const part of parts) { let eventType = 'message'; let dataStr = ''; for (const line of part.split('\n')) { if (line.startsWith('event: ')) { eventType = line.slice(7).trim(); } else if (line.startsWith('data: ')) { dataStr += line.slice(6); } } if (dataStr) { try { const data = JSON.parse(dataStr); onEvent(eventType, data); } catch (e) { console.warn('Failed to parse SSE data:', dataStr); } } } } } ``` ### Building the Segments Array (React Example) ```js // segments: Array<{ type: 'text', content: string } | { type: 'tool', tool, args?, result?, success?, error?, status }> let segments = []; streamChat(mcpBffUrl, headers, userMessage, conversationId, (event, data) => { switch (event) { case 'start': conversationId = data.conversationId; segments = []; break; case 'text': { const last = segments[segments.length - 1]; if (last && last.type === 'text') { last.content += data.content; // append to current text segment } else { segments.push({ type: 'text', content: data.content }); // new text segment } rerenderBubble(segments); break; } case 'tool_start': // push a new tool segment — this "cuts" the text flow segments.push({ type: 'tool', tool: data.tool, status: 'running' }); rerenderBubble(segments); break; case 'tool_executing': { const toolSeg = findLastToolSegment(segments, data.tool); if (toolSeg) toolSeg.args = data.args; rerenderBubble(segments); break; } case 'tool_result': { const toolSeg = findLastToolSegment(segments, data.tool); if (toolSeg) { toolSeg.status = data.success ? 'complete' : 'error'; toolSeg.result = data.result; toolSeg.error = data.error; toolSeg.success = data.success; // Check for frontend action (QR code, data view, payment, secret) toolSeg.frontendAction = extractFrontendAction(data.result); } rerenderBubble(segments); break; } case 'error': segments.push({ type: 'text', content: `**Error:** ${data.message}` }); rerenderBubble(segments); break; case 'done': // Store final metadata (processingTime, aliasMapSummary) for the message finalizeMessage(segments, data); break; } }); function findLastToolSegment(segments, toolName) { for (let i = segments.length - 1; i >= 0; i--) { if (segments[i].type === 'tool' && segments[i].tool === toolName) return segments[i]; } return null; } ``` ### Rendering the Message Bubble Render each segment in order inside a single assistant message bubble: ```jsx function AssistantMessageBubble({ segments }) { return (
{segments.map((segment, i) => { if (segment.type === 'text') { return ; } if (segment.type === 'tool') { if (segment.frontendAction) { return ; } return ; } return null; })}
); } function ToolCard({ segment }) { const isRunning = segment.status === 'running'; const isError = segment.status === 'error'; return (
{isRunning && } {segment.tool} {!isRunning && (isError ? : )}
{segment.args && (
{JSON.stringify(segment.args, null, 2)}
)} {segment.result && (
{JSON.stringify(segment.result, null, 2)}
)} {segment.error &&
{segment.error}
}
); } ``` The tool card should be compact by default (just tool name + status icon) with collapsible sections for args and result, so it doesn't dominate the reading flow. While a tool is running (`status: 'running'`), show a spinner. When complete, show a check or error icon. ### Handling `__frontendAction` in Tool Results When the AI calls certain tools (e.g., QR code, data view, payment, secret reveal), the tool result contains a `__frontendAction` object. This signals the frontend to render a special UI component **inline in the bubble at the tool segment's position** instead of the default collapsible ToolCard. This is already handled in the segments code above — when `segment.frontendAction` is present, render an `ActionCard` instead of a `ToolCard`. The `extractFrontendAction` helper unwraps the action from various MCP response formats: ```js function extractFrontendAction(result) { if (!result) return null; if (result.__frontendAction) return result.__frontendAction; // Unwrap MCP wrapper format: result → result.result → content[].text → JSON let data = result; if (result?.result?.content) data = result.result; if (data?.content && Array.isArray(data.content)) { const textContent = data.content.find(c => c.type === 'text'); if (textContent?.text) { try { const parsed = JSON.parse(textContent.text); if (parsed?.__frontendAction) return parsed.__frontendAction; } catch { /* not JSON */ } } } return null; } ``` ### Frontend Action Types | Action Type | Component | Description | |-------------|-----------|-------------| | `qrcode` | `QrCodeActionCard` | Renders any string value as a QR code card | | `dataView` | `DataViewActionCard` | Fetches a Business API route and renders a grid or gallery | | `payment` | `PaymentActionCard` | "Pay Now" button that opens Stripe checkout modal | #### QR Code Action (`type: "qrcode"`) Triggered by the `showQrCode` MCP tool. Renders a QR code card from any string value. ```json { "__frontendAction": { "type": "qrcode", "value": "https://example.com/invite/ABC123", "title": "Invite Link", "subtitle": "Scan to open" } } ``` #### Data View Action (`type: "dataView"`) Triggered by `showBusinessApiListInFrontEnd` or `showBusinessApiGalleryInFrontEnd`. Frontend calls the provided Business API route using the user's bearer token, then renders: - `viewType: "grid"` as tabular rows/columns - `viewType: "gallery"` as image-first cards ```json { "__frontendAction": { "type": "dataView", "viewType": "grid", "title": "Recent Orders", "serviceName": "commerce", "apiName": "listOrders", "routePath": "/v1/listorders", "httpMethod": "GET", "queryParams": { "pageNo": 1, "pageRowCount": 10 }, "columns": [ { "field": "id", "label": "Order ID" }, { "field": "orderAmount", "label": "Amount", "format": "currency" } ] } } ``` #### Payment Action (`type: "payment"`) Triggered by the `initiatePayment` MCP tool. Renders a payment card with amount and a "Pay Now" button. ```json { "__frontendAction": { "type": "payment", "orderId": "uuid", "orderType": "order", "serviceName": "commerce", "amount": 99.99, "currency": "USD", "description": "Order #abc123" } } ``` ### Conversation Management ```js // List user's conversations GET /api/chat/conversations // Get conversation history GET /api/chat/conversations/:conversationId // Delete a conversation DELETE /api/chat/conversations/:conversationId ``` --- ## MCP Tool Discovery & Direct Invocation The MCP BFF exposes endpoints for discovering and directly calling MCP tools (useful for debugging or building custom UIs). ### GET /api/tools — List All Tools ```js const response = await fetch(`${mcpBffUrl}/api/tools`, { headers }); const { tools, count } = await response.json(); // tools: [{ name, description, inputSchema, service }, ...] ``` ### GET /api/tools/service/:serviceName — List Service Tools ```js const response = await fetch(`${mcpBffUrl}/api/tools/service/commerce`, { headers }); const { tools } = await response.json(); ``` ### POST /api/tools/call — Call a Tool Directly ```js const response = await fetch(`${mcpBffUrl}/api/tools/call`, { method: 'POST', headers, body: JSON.stringify({ toolName: "listProducts", args: { page: 1, limit: 10 }, }), }); const result = await response.json(); ``` ### GET /api/tools/status — Connection Status ```js const status = await fetch(`${mcpBffUrl}/api/tools/status`, { headers }); // Returns health of each MCP service connection ``` ### POST /api/tools/refresh — Reconnect Services ```js await fetch(`${mcpBffUrl}/api/tools/refresh`, { method: 'POST', headers }); // Reconnects to all MCP services and refreshes the tool registry ``` --- ## Elasticsearch API The MCP BFF provides direct access to Elasticsearch for searching, filtering, and aggregating data across all project indices. All Elasticsearch endpoints are under `/api/elastic`. ### GET /api/elastic/allIndices — List Project Indices Returns all Elasticsearch indices belonging to this project (prefixed with `auteurlabb_`). ```js const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers }); // ["auteurlabb_products", "auteurlabb_orders", ...] ``` ### POST /api/elastic/:indexName/rawsearch — Raw Elasticsearch Query Execute a raw Elasticsearch query on a specific index. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/products/rawsearch`, { method: 'POST', headers, body: JSON.stringify({ query: { bool: { must: [ { match: { status: "active" } }, { range: { price: { gte: 10, lte: 100 } } } ] } }, size: 20, from: 0, sort: [{ createdAt: "desc" }] }), }); const { total, hits, aggregations, took } = await response.json(); // hits: [{ _id, _index, _score, _source: { ...document... } }, ...] ``` Note: The index name is automatically prefixed with `auteurlabb_` if not already prefixed. ### POST /api/elastic/:indexName/search — Simplified Search A higher-level search API with built-in support for filters, sorting, and pagination. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/products/search`, { method: 'POST', headers, body: JSON.stringify({ search: "wireless headphones", // Full-text search filters: { status: "active" }, // Field filters sort: { field: "createdAt", order: "desc" }, page: 1, limit: 25, }), }); ``` ### POST /api/elastic/:indexName/aggregate — Aggregations Run aggregation queries for analytics and dashboards. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/orders/aggregate`, { method: 'POST', headers, body: JSON.stringify({ aggs: { status_counts: { terms: { field: "status.keyword" } }, total_revenue: { sum: { field: "amount" } }, monthly_orders: { date_histogram: { field: "createdAt", calendar_interval: "month" } } }, query: { range: { createdAt: { gte: "now-1y" } } } }), }); ``` ### GET /api/elastic/:indexName/mapping — Index Mapping Get the field mapping for an index (useful for building dynamic filter UIs). ```js const mapping = await fetch(`${mcpBffUrl}/api/elastic/products/mapping`, { headers }); ``` ### POST /api/elastic/:indexName/ai-search — AI-Assisted Search Uses the configured AI model to convert a natural-language query into an Elasticsearch query. ```js const response = await fetch(`${mcpBffUrl}/api/elastic/orders/ai-search`, { method: 'POST', headers, body: JSON.stringify({ query: "orders over $100 from last month that are still pending", }), }); // Returns: { total, hits, generatedQuery, ... } ``` --- ## Log API The MCP BFF provides log viewing endpoints for monitoring application behavior. ### GET /api/logs — Query Logs ```js const response = await fetch(`${mcpBffUrl}/api/logs?page=1&limit=50&logType=2&service=commerce&search=payment`, { headers, }); ``` **Query Parameters:** - `page` — Page number (default: 1) - `limit` — Items per page (default: 50) - `logType` — 0=INFO, 1=WARNING, 2=ERROR - `service` — Filter by service name - `search` — Search in subject and message - `from` / `to` — Date range (ISO strings) - `requestId` — Filter by request ID ### GET /api/logs/stream — Real-time Console Stream (SSE) Streams real-time console output from all services via Server-Sent Events. ```js const eventSource = new EventSource(`${mcpBffUrl}/api/logs/stream?services=commerce,auth`, { headers: { 'Authorization': `Bearer ${accessToken}` }, }); eventSource.addEventListener('log', (event) => { const logEntry = JSON.parse(event.data); // { service, timestamp, level, message, ... } }); ``` --- ## Available Services The MCP BFF connects to the following backend services: | Service | Description | |---------|-------------| | `auth` | Authentication, user management, sessions | | `projectPortfolio` | Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership. | | `messagingCenter` | Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations. | | `moderationAdmin` | Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance. | | `agentHub` | AI Agent Hub | Each service exposes MCP tools that the AI can call through the BFF. Use `GET /api/tools` to discover all available tools at runtime, or `GET /api/tools/service/:serviceName` to list tools for a specific service. --- ## MCP as Internal API Gateway The MCP-BFF service can also be used by the frontend as an **internal API gateway** for tool-based interactions. This is separate from external AI tool connections — it is meant for frontend code that needs to call backend tools programmatically. ### Direct Tool Calls (REST) Use the REST tool invocation endpoints for programmatic access from frontend code: ```js // List all available tools const tools = await fetch(`${mcpBffUrl}/api/tools`, { headers }); // Call a specific tool directly const result = await fetch(`${mcpBffUrl}/api/tools/call`, { method: 'POST', headers, body: JSON.stringify({ toolName: 'listProducts', args: { page: 1, limit: 10 }, }), }); ``` ### AI-Orchestrated Calls (Chat API) For AI-driven interactions, use the chat streaming API documented above (`POST /api/chat/stream`). The AI model decides which tools to call based on the user's message. Both approaches use the user's JWT access token for authentication — the MCP-BFF forwards it to the correct backend service. --- ## MCP Connection Info for Profile Page The user's **profile page** should include an informational section explaining how to connect external AI tools (Cursor, Claude Desktop, Lovable, Windsurf, etc.) to this application's backend via MCP. ### What to Display The MCP-BFF exposes a **unified MCP endpoint** that aggregates tools from all backend services into a single connection point: | Environment | URL | |-------------|-----| | **Preview** | `https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp` | | **Staging** | `https://auteurlabb-stage.mindbricks.co/mcpbff-api/mcp` | | **Production** | `https://auteurlabb.mindbricks.co/mcpbff-api/mcp` | For legacy MCP clients that don't support StreamableHTTP, an SSE fallback is available at the same URL with `/sse` appended (e.g., `.../mcpbff-api/mcp/sse`). ### Profile Page UI Requirements Add an **"MCP Connection"** or **"Connect External AI Tools"** card/section to the profile page with: 1. **Endpoint URL** — Display the MCP endpoint URL for the current environment with a copy-to-clipboard button. 2. **Ready-to-Copy Configs** — Show copy-to-clipboard config snippets for popular tools: **Cursor** (`.cursor/mcp.json`): ```json { "mcpServers": { "auteurlabb": { "url": "https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } } ``` **Claude Desktop** (`claude_desktop_config.json`): ```json { "mcpServers": { "auteurlabb": { "url": "https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } } ``` 3. **Auth Note** — Note that users should replace `your_access_token_here` with a valid JWT access token from the login API. 4. **OAuth Note** — Display a note that OAuth authentication is not currently supported for MCP connections. 5. **Available Tools** — Optionally show a summary of available tool categories (e.g., "CRUD operations for all data objects, custom business APIs, file operations") or link to the tools discovery endpoint (`GET /api/tools`). --- **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - ProjectPortfolio Service** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of projectPortfolio ## Service Access ProjectPortfolio service management is handled through service specific base urls. ProjectPortfolio service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the projectPortfolio service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/projectportfolio-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/projectportfolio-api` * **Production:** `https://auteurlabb.mindbricks.co/projectportfolio-api` ## Scope **ProjectPortfolio Service Description** Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership. ProjectPortfolio service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`filmProject` Data Object**: A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status. **`accessGrant` Data Object**: Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied). **`projectBookmark` Data Object**: User bookmarks/follows for projects. Each bookmark is per user+project. **`investmentOffer` Data Object**: Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn). **`userFollow` Data Object**: Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor). ## ProjectPortfolio Service Frontend Description By The Backend Architect # ProjectPortfolio Service Use this service to browse, submit, access, and manage film projects. Project listings, details, bookmarks, and access requests are all managed here. Filmmakers/studios can control project visibility. Investors can search, request access, and bookmark. Admins can moderate, approve, and oversee lifecycle transitions. All project API responses may include owner/studio data via selectJoin when needed. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## FilmProject Data Object A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status. ### FilmProject Data Object Frontend Description By The Backend Architect - Owners (filmmaker/studio) can submit, edit, withdraw projects. - Admins approve/reject projects. Only approved & public projects are visible to all; private = access grants required. - Investors can request/bookmark. Normal users can only view public, approved projects. - UI should show current approver, access policy, and owner(s) on detail. ### FilmProject Data Object Properties FilmProject data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `title` | String | false | Yes | No | Project title, unique per owner | | `description` | Text | false | Yes | No | Project description (for details page/fulltext search) | | `synopsis` | Text | false | No | No | Short synopsis or tagline | | `budget` | Double | false | Yes | No | Estimated budget (USD) | | `cast` | String | true | No | No | List of major cast members (names) | | `genre` | String | true | No | No | Project genres/tags | | `projectType` | Enum | false | Yes | No | Origin: filmmaker or studio | | `ownerUserId` | ID | false | Yes | No | User ID of project owner (filmmaker/studio admin) | | `studioId` | ID | false | No | No | (Optional) User ID of the studio (for studio projects) | | `isPublic` | Boolean | false | Yes | No | Project public visibility flag | | `approvalStatus` | Enum | false | Yes | No | Project approval/publication workflow status | | `mediaUrls` | String | true | No | No | Project demo reel/trailer/cover media URLs | | `featured` | Boolean | false | No | No | Platform feature flag (for promoted projects) | | `publishedAt` | Date | false | No | No | Publication date | | `accessPolicy` | Enum | false | Yes | No | Access policy (open: any authorized user, restricted: need grant) | | `director` | String | false | No | No | Director of the film project | | `fundingGoal` | Double | false | No | No | Funding goal amount (USD) | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Array Properties `cast` `genre` `mediaUrls` Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **projectType**: [filmmaker, studio] - **approvalStatus**: [pending, approved, rejected, withdrawn] - **accessPolicy**: [open, restricted] ### Relation Properties `ownerUserId` `studioId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **ownerUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **studioId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `title` `description` `synopsis` `budget` `genre` `projectType` `isPublic` `approvalStatus` `featured` `accessPolicy` `director` `fundingGoal` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **title**: String has a filter named `title` - **description**: Text has a filter named `description` - **synopsis**: Text has a filter named `synopsis` - **budget**: Double has a filter named `budget` - **genre**: String has a filter named `genre` - **projectType**: Enum has a filter named `projectType` - **isPublic**: Boolean has a filter named `isPublic` - **approvalStatus**: Enum has a filter named `approvalStatus` - **featured**: Boolean has a filter named `featured` - **accessPolicy**: Enum has a filter named `accessPolicy` - **director**: String has a filter named `director` - **fundingGoal**: Double has a filter named `fundingGoal` ## AccessGrant Data Object Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied). ### AccessGrant Data Object Frontend Description By The Backend Architect - For private (restricted) projects, this governs who can view the project in detail. - Only owner/admin can grant/revoke directly; others can request (status=requested). - Each grant/deny/revoke/change tracks who, when, and why; direct mapping to UI access control modals. ### AccessGrant Data Object Properties AccessGrant data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `projectId` | ID | false | Yes | No | Film project ID for which access is granted/requested | | `granteeUserId` | ID | false | Yes | No | ID of user being granted/requesting access | | `grantedByUserId` | ID | false | No | No | Who granted/revoked the access (or null for self-request) | | `status` | Enum | false | Yes | No | requested (pending); granted (success); revoked; denied | | `requestMessage` | Text | false | No | No | Message from requester (for context) | | `dateGranted` | Date | false | No | No | Timestamp when access status last updated | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [requested, granted, revoked, denied] ### Relation Properties `projectId` `granteeUserId` `grantedByUserId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **projectId**: ID Relation to `filmProject`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **granteeUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **grantedByUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `projectId` `granteeUserId` `status` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **projectId**: ID has a filter named `projectId` - **granteeUserId**: ID has a filter named `granteeUserId` - **status**: Enum has a filter named `status` ## ProjectBookmark Data Object User bookmarks/follows for projects. Each bookmark is per user+project. ### ProjectBookmark Data Object Frontend Description By The Backend Architect - Users can bookmark projects for easy quick access. - Bookmark is per-user & per-project. User can view, add, and remove their own bookmarks only. ### ProjectBookmark Data Object Properties ProjectBookmark data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `projectId` | ID | false | Yes | No | The project being bookmarked | | `userId` | ID | false | Yes | No | The user who bookmarked this project | | `createdAtBookmark` | Date | false | No | No | When bookmark was made | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Relation Properties `projectId` `userId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **projectId**: ID Relation to `filmProject`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **userId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### Filter Properties `projectId` `userId` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **projectId**: ID has a filter named `projectId` - **userId**: ID has a filter named `userId` ## InvestmentOffer Data Object Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn). ### InvestmentOffer Data Object Properties InvestmentOffer data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `projectId` | ID | false | Yes | No | Film project receiving the investment offer | | `investorUserId` | ID | false | Yes | No | Investor who made the offer | | `offerAmount` | Double | false | Yes | No | Investment amount in USD | | `message` | Text | false | No | No | Cover letter or terms from the investor | | `status` | Enum | false | No | No | Offer lifecycle status | | `respondedAt` | Date | false | No | No | When the project owner responded | | `responseNote` | Text | false | No | No | Project owner note on accept/reject | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [pending, accepted, rejected, withdrawn] ### Relation Properties `projectId` `investorUserId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **projectId**: ID Relation to `filmProject`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **investorUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### Filter Properties `projectId` `investorUserId` `offerAmount` `status` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **projectId**: ID has a filter named `projectId` - **investorUserId**: ID has a filter named `investorUserId` - **offerAmount**: Double has a filter named `offerAmount` - **status**: Enum has a filter named `status` ## UserFollow Data Object Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor). ### UserFollow Data Object Properties UserFollow data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `followerUserId` | ID | false | Yes | No | The user who is following | | `followingUserId` | ID | false | Yes | No | The user being followed | | `followedAt` | Date | false | No | No | When the follow relationship was created | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Relation Properties `followerUserId` `followingUserId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **followerUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **followingUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### Filter Properties `followerUserId` `followingUserId` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **followerUserId**: ID has a filter named `followerUserId` - **followingUserId**: ID has a filter named `followingUserId` ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### FilmProject Default APIs **Display Label Property:** `title` — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references). | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createFilmProject` | `/v1/filmprojects` | Yes | | Update | `updateFilmProject` | `/v1/filmprojects/:filmProjectId` | Yes | | Delete | _none_ | - | Auto | | Get | `getFilmProject` | `/v1/filmprojects/:filmProjectId` | Yes | | List | `listFilmProjects` | `/v1/filmprojects` | Yes | ### AccessGrant Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAccessGrant` | `/v1/accessgrants` | Yes | | Update | `updateAccessGrant` | `/v1/accessgrants/:accessGrantId` | Yes | | Delete | _none_ | - | Auto | | Get | `getAccessGrant` | `/v1/accessgrants/:accessGrantId` | Yes | | List | `listAccessGrants` | `/v1/accessgrants` | Yes | ### ProjectBookmark Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createBookmark` | `/v1/bookmark` | Yes | | Update | _none_ | - | Auto | | Delete | `deleteBookmark` | `/v1/bookmark/:projectBookmarkId` | Yes | | Get | _none_ | - | Auto | | List | `listBookmarks` | `/v1/bookmarks` | Yes | ### InvestmentOffer Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createInvestmentOffer` | `/v1/investmentoffers` | Yes | | Update | `respondToInvestmentOffer` | `/v1/respondtoinvestmentoffer/:investmentOfferId` | Yes | | Delete | _none_ | - | Auto | | Get | _none_ | - | Auto | | List | `listInvestmentOffers` | `/v1/investmentoffers` | Yes | ### UserFollow Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `followUser` | `/v1/followuser` | Yes | | Update | _none_ | - | Auto | | Delete | `unfollowUser` | `/v1/unfollowuser/:userFollowId` | Yes | | Get | _none_ | - | Auto | | List | `listUserFollows` | `/v1/userfollows` | Yes | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Create Filmproject` API **[Default create API]** — This is the designated default `create` API for the `filmProject` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Submit a new film project (by filmmaker/studio). Sets approvalStatus=pending and assigns ownerUserId from session. Studio projects require studioId. **API Frontend Description By The Backend Architect** Used by filmmakers/studios to submit a new project. Standard create form. Approval workflow starts automatically. Owner assigned from session. **Rest Route** The `createFilmProject` API REST controller can be triggered via the following route: `/v1/filmprojects` **Rest Request Parameters** The `createFilmProject` api has got 15 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | title | String | true | request.body?.["title"] | | description | Text | true | request.body?.["description"] | | synopsis | Text | false | request.body?.["synopsis"] | | budget | Double | true | request.body?.["budget"] | | cast | String | false | request.body?.["cast"] | | genre | String | false | request.body?.["genre"] | | projectType | Enum | true | request.body?.["projectType"] | | studioId | ID | false | request.body?.["studioId"] | | isPublic | Boolean | true | request.body?.["isPublic"] | | mediaUrls | String | false | request.body?.["mediaUrls"] | | featured | Boolean | false | request.body?.["featured"] | | publishedAt | Date | false | request.body?.["publishedAt"] | | accessPolicy | Enum | true | request.body?.["accessPolicy"] | | director | String | false | request.body?.["director"] | | fundingGoal | Double | false | request.body?.["fundingGoal"] | **title** : Project title, unique per owner **description** : Project description (for details page/fulltext search) **synopsis** : Short synopsis or tagline **budget** : Estimated budget (USD) **cast** : List of major cast members (names) **genre** : Project genres/tags **projectType** : Origin: filmmaker or studio **studioId** : (Optional) User ID of the studio (for studio projects) **isPublic** : Project public visibility flag **mediaUrls** : Project demo reel/trailer/cover media URLs **featured** : Platform feature flag (for promoted projects) **publishedAt** : Publication date **accessPolicy** : Access policy (open: any authorized user, restricted: need grant) **director** : Director of the film project **fundingGoal** : Funding goal amount (USD) **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/filmprojects** ```js axios({ method: 'POST', url: '/v1/filmprojects', data: { title:"String", description:"Text", synopsis:"Text", budget:"Double", cast:"String", genre:"String", projectType:"Enum", studioId:"ID", isPublic:"Boolean", mediaUrls:"String", featured:"Boolean", publishedAt:"Date", accessPolicy:"Enum", director:"String", fundingGoal:"Double", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "filmProject", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "filmProject": { "id": "ID", "title": "String", "description": "Text", "synopsis": "Text", "budget": "Double", "cast": "String", "genre": "String", "projectType": "Enum", "projectType_idx": "Integer", "ownerUserId": "ID", "studioId": "ID", "isPublic": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "mediaUrls": "String", "featured": "Boolean", "publishedAt": "Date", "accessPolicy": "Enum", "accessPolicy_idx": "Integer", "director": "String", "fundingGoal": "Double", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Filmproject` API **[Default update API]** — This is the designated default `update` API for the `filmProject` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a film project. Only the owner or admin can update. Only admin can set approvalStatus=approved/rejected. Owner can withdraw (approvalStatus=withdrawn). **API Frontend Description By The Backend Architect** For editing project details (including withdrawal). ApprovalStatus can only be changed by admin (other than withdrawn by owner). Owner cannot submit direct publish/approve requests; always wait admin. **Rest Route** The `updateFilmProject` API REST controller can be triggered via the following route: `/v1/filmprojects/:filmProjectId` **Rest Request Parameters** The `updateFilmProject` api has got 15 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | filmProjectId | ID | true | request.params?.["filmProjectId"] | | title | String | false | request.body?.["title"] | | description | Text | false | request.body?.["description"] | | synopsis | Text | false | request.body?.["synopsis"] | | budget | Double | false | request.body?.["budget"] | | cast | String | false | request.body?.["cast"] | | genre | String | false | request.body?.["genre"] | | isPublic | Boolean | false | request.body?.["isPublic"] | | approvalStatus | Enum | true | request.body?.["approvalStatus"] | | mediaUrls | String | false | request.body?.["mediaUrls"] | | featured | Boolean | false | request.body?.["featured"] | | publishedAt | Date | false | request.body?.["publishedAt"] | | accessPolicy | Enum | false | request.body?.["accessPolicy"] | | director | String | false | request.body?.["director"] | | fundingGoal | Double | false | request.body?.["fundingGoal"] | **filmProjectId** : This id paremeter is used to select the required data object that will be updated **title** : Project title, unique per owner **description** : Project description (for details page/fulltext search) **synopsis** : Short synopsis or tagline **budget** : Estimated budget (USD) **cast** : List of major cast members (names) **genre** : Project genres/tags **isPublic** : Project public visibility flag **approvalStatus** : Project approval/publication workflow status **mediaUrls** : Project demo reel/trailer/cover media URLs **featured** : Platform feature flag (for promoted projects) **publishedAt** : Publication date **accessPolicy** : Access policy (open: any authorized user, restricted: need grant) **director** : Director of the film project **fundingGoal** : Funding goal amount (USD) **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/filmprojects/:filmProjectId** ```js axios({ method: 'PATCH', url: `/v1/filmprojects/${filmProjectId}`, data: { title:"String", description:"Text", synopsis:"Text", budget:"Double", cast:"String", genre:"String", isPublic:"Boolean", approvalStatus:"Enum", mediaUrls:"String", featured:"Boolean", publishedAt:"Date", accessPolicy:"Enum", director:"String", fundingGoal:"Double", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "filmProject", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "filmProject": { "id": "ID", "title": "String", "description": "Text", "synopsis": "Text", "budget": "Double", "cast": "String", "genre": "String", "projectType": "Enum", "projectType_idx": "Integer", "ownerUserId": "ID", "studioId": "ID", "isPublic": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer", "mediaUrls": "String", "featured": "Boolean", "publishedAt": "Date", "accessPolicy": "Enum", "accessPolicy_idx": "Integer", "director": "String", "fundingGoal": "Double", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, "ownerUser": {} } ``` ### `Get Filmproject` API **[Default get API]** — This is the designated default `get` API for the `filmProject` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch project details. Accessible by owner, admin, or for public + approved projects. Also for granted investors/users (accessGrant). **API Frontend Description By The Backend Architect** Used to display project details page. Applies access and visibility policy -- if project is private, only owner/admin/granted users can see; if public+approved, visible to everyone logged in. User denied access gets 404. **Rest Route** The `getFilmProject` API REST controller can be triggered via the following route: `/v1/filmprojects/:filmProjectId` **Rest Request Parameters** The `getFilmProject` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | filmProjectId | ID | true | request.params?.["filmProjectId"] | **filmProjectId** : 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/filmprojects/:filmProjectId** ```js axios({ method: 'GET', url: `/v1/filmprojects/${filmProjectId}`, 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": "filmProject", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "filmProject": { "ownerUser": { "fullname": "String", "avatar": "String", "roleId": "String" }, "studio": { "fullname": "String", "avatar": "String", "roleId": "String" }, "isActive": true } } ``` ### `List Filmprojects` API **[Default list API]** — This is the designated default `list` API for the `filmProject` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List projects (public+approved, owned, or where granted). With filters for search. Results by role: owner/all their projects; normal users see only public+approved; investors/studios see owned or accessible, or public+approved. Filters: genre, budget, approvalStatus, isPublic, featured, projectType, title, description (text search). **API Frontend Description By The Backend Architect** Allows all users to search/browse projects. Only public/approved projects are visible to normal users; owners/investors get private projects to which they're granted. Search by genre, budget, etc. Use for the main project directory. **Rest Route** The `listFilmProjects` API REST controller can be triggered via the following route: `/v1/filmprojects` **Rest Request Parameters** The `listFilmProjects` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/filmprojects** ```js axios({ method: 'GET', url: '/v1/filmprojects', 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": "filmProjects", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "filmProjects": [ { "ownerUser": [ { "fullname": "String", "avatar": "String", "roleId": "String" }, {}, {} ], "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Accessgrant` API **[Default create API]** — This is the designated default `create` API for the `accessGrant` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new accessGrant. Used for access requests (user) or direct grant (owner/admin). **API Frontend Description By The Backend Architect** Investors request access to private/restricted projects; project owners or admins grant/revoke access to users. Status flows: requested→granted/denied/revoked. Owner can only grant/revoke their own; admins can manage all. **Rest Route** The `createAccessGrant` API REST controller can be triggered via the following route: `/v1/accessgrants` **Rest Request Parameters** The `createAccessGrant` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | projectId | ID | true | request.body?.["projectId"] | | granteeUserId | ID | true | request.body?.["granteeUserId"] | | grantedByUserId | ID | false | request.body?.["grantedByUserId"] | | status | Enum | true | request.body?.["status"] | | requestMessage | Text | false | request.body?.["requestMessage"] | | dateGranted | Date | false | request.body?.["dateGranted"] | **projectId** : Film project ID for which access is granted/requested **granteeUserId** : ID of user being granted/requesting access **grantedByUserId** : Who granted/revoked the access (or null for self-request) **status** : requested (pending); granted (success); revoked; denied **requestMessage** : Message from requester (for context) **dateGranted** : Timestamp when access status last updated **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/accessgrants** ```js axios({ method: 'POST', url: '/v1/accessgrants', data: { projectId:"ID", granteeUserId:"ID", grantedByUserId:"ID", status:"Enum", requestMessage:"Text", dateGranted:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "accessGrant", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "accessGrant": { "id": "ID", "projectId": "ID", "granteeUserId": "ID", "grantedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "requestMessage": "Text", "dateGranted": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Update Accessgrant` API **[Default update API]** — This is the designated default `update` API for the `accessGrant` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update status of an access grant. Only admin or project owner can grant, revoke, or deny. User can cancel (delete) their own pending request or see status. **API Frontend Description By The Backend Architect** Used for access management UI. Owners/admins can grant/revoke/deny access grants; requesters can cancel. For status transitions, always log who did it and when. Only valid transitions possible (ex: can't grant if not owner/admin). **Rest Route** The `updateAccessGrant` API REST controller can be triggered via the following route: `/v1/accessgrants/:accessGrantId` **Rest Request Parameters** The `updateAccessGrant` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | accessGrantId | ID | true | request.params?.["accessGrantId"] | | status | Enum | true | request.body?.["status"] | | requestMessage | Text | false | request.body?.["requestMessage"] | | dateGranted | Date | false | request.body?.["dateGranted"] | **accessGrantId** : This id paremeter is used to select the required data object that will be updated **status** : requested (pending); granted (success); revoked; denied **requestMessage** : Message from requester (for context) **dateGranted** : Timestamp when access status last updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/accessgrants/:accessGrantId** ```js axios({ method: 'PATCH', url: `/v1/accessgrants/${accessGrantId}`, data: { status:"Enum", requestMessage:"Text", dateGranted:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "accessGrant", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "accessGrant": { "id": "ID", "projectId": "ID", "granteeUserId": "ID", "grantedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "requestMessage": "Text", "dateGranted": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Accessgrant` API **[Default get API]** — This is the designated default `get` API for the `accessGrant` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single accessGrant record by id. Used for grant management UI. **API Frontend Description By The Backend Architect** Shows a single access grant: who, for what project, current status, request message. **Rest Route** The `getAccessGrant` API REST controller can be triggered via the following route: `/v1/accessgrants/:accessGrantId` **Rest Request Parameters** The `getAccessGrant` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | accessGrantId | ID | true | request.params?.["accessGrantId"] | **accessGrantId** : 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/accessgrants/:accessGrantId** ```js axios({ method: 'GET', url: `/v1/accessgrants/${accessGrantId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "accessGrant", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "accessGrant": { "id": "ID", "projectId": "ID", "granteeUserId": "ID", "grantedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "requestMessage": "Text", "dateGranted": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Accessgrants` API **[Default list API]** — This is the designated default `list` API for the `accessGrant` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all accessGrants for a project (owner/admin) or for a user (user's own requests). **API Frontend Description By The Backend Architect** Used by project owners/admins to see all access requests; by users to see their own requests & statuses. Investors check their granted projects for dashboard; owners manage through this list. **Rest Route** The `listAccessGrants` API REST controller can be triggered via the following route: `/v1/accessgrants` **Rest Request Parameters** **Filter Parameters** The `listAccessGrants` api supports 3 optional filter parameters for filtering list results: **projectId** (`ID`): Film project ID for which access is granted/requested - Single: `?projectId=` - Multiple: `?projectId=&projectId=` - Null: `?projectId=null` **granteeUserId** (`ID`): ID of user being granted/requesting access - Single: `?granteeUserId=` - Multiple: `?granteeUserId=&granteeUserId=` - Null: `?granteeUserId=null` **status** (`Enum`): requested (pending); granted (success); revoked; denied - 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/accessgrants** ```js axios({ method: 'GET', url: '/v1/accessgrants', data: { }, params: { // Filter parameters (see Filter Parameters section above) // projectId: '' // Filter by projectId // granteeUserId: '' // Filter by granteeUserId // 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": "accessGrants", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "accessGrants": [ { "id": "ID", "projectId": "ID", "granteeUserId": "ID", "grantedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "requestMessage": "Text", "dateGranted": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Bookmark` API **[Default create API]** — This is the designated default `create` API for the `projectBookmark` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Add a project bookmark (user/project pair, unique). **API Frontend Description By The Backend Architect** Users bookmark projects for easy retrieval. Only one bookmark per (user, project). **Rest Route** The `createBookmark` API REST controller can be triggered via the following route: `/v1/bookmark` **Rest Request Parameters** The `createBookmark` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | projectId | ID | true | request.body?.["projectId"] | **projectId** : The project being bookmarked **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/bookmark** ```js axios({ method: 'POST', url: '/v1/bookmark', data: { projectId:"ID", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "projectBookmark", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "projectBookmark": { "id": "ID", "projectId": "ID", "userId": "ID", "createdAtBookmark": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Delete Bookmark` API **[Default delete API]** — This is the designated default `delete` API for the `projectBookmark` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Remove a project bookmark (user can only delete their own bookmarks). **API Frontend Description By The Backend Architect** Bookmarks are always per-user: can only remove bookmark if you're the owner. **Rest Route** The `deleteBookmark` API REST controller can be triggered via the following route: `/v1/bookmark/:projectBookmarkId` **Rest Request Parameters** The `deleteBookmark` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | projectBookmarkId | ID | true | request.params?.["projectBookmarkId"] | **projectBookmarkId** : 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/bookmark/:projectBookmarkId** ```js axios({ method: 'DELETE', url: `/v1/bookmark/${projectBookmarkId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "projectBookmark", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "projectBookmark": { "id": "ID", "projectId": "ID", "userId": "ID", "createdAtBookmark": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `List Bookmarks` API **[Default list API]** — This is the designated default `list` API for the `projectBookmark` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List a user's own bookmarks. Only accessible for current user. Used for profile/bookmarks view. **API Frontend Description By The Backend Architect** Used for the user's My Bookmarks page. Always lists only YOUR bookmarks, never others'. **Rest Route** The `listBookmarks` API REST controller can be triggered via the following route: `/v1/bookmarks` **Rest Request Parameters** **Filter Parameters** The `listBookmarks` api supports 2 optional filter parameters for filtering list results: **projectId** (`ID`): The project being bookmarked - Single: `?projectId=` - Multiple: `?projectId=&projectId=` - Null: `?projectId=null` **userId** (`ID`): The user who bookmarked this project - 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/bookmarks** ```js axios({ method: 'GET', url: '/v1/bookmarks', data: { }, params: { // Filter parameters (see Filter Parameters section above) // projectId: '' // Filter by projectId // 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": "projectBookmarks", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "projectBookmarks": [ { "id": "ID", "projectId": "ID", "userId": "ID", "createdAtBookmark": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Investmentoffer` API **[Default create API]** — This is the designated default `create` API for the `investmentOffer` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Investor sends an investment offer to a film project. Status defaults to pending. Only investors can create offers. **Rest Route** The `createInvestmentOffer` API REST controller can be triggered via the following route: `/v1/investmentoffers` **Rest Request Parameters** The `createInvestmentOffer` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | projectId | ID | true | request.body?.["projectId"] | | offerAmount | Double | true | request.body?.["offerAmount"] | | message | Text | false | request.body?.["message"] | | respondedAt | Date | false | request.body?.["respondedAt"] | | responseNote | Text | false | request.body?.["responseNote"] | **projectId** : Film project receiving the investment offer **offerAmount** : Investment amount in USD **message** : Cover letter or terms from the investor **respondedAt** : When the project owner responded **responseNote** : Project owner note on accept/reject **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/investmentoffers** ```js axios({ method: 'POST', url: '/v1/investmentoffers', data: { projectId:"ID", offerAmount:"Double", message:"Text", respondedAt:"Date", responseNote:"Text", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "investmentOffer", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "investmentOffer": { "id": "ID", "projectId": "ID", "investorUserId": "ID", "offerAmount": "Double", "message": "Text", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "responseNote": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Respond Toinvestmentoffer` API **[Default update API]** — This is the designated default `update` API for the `investmentOffer` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Project owner accepts or rejects an investment offer. Only the project owner or admin can respond. **Rest Route** The `respondToInvestmentOffer` API REST controller can be triggered via the following route: `/v1/respondtoinvestmentoffer/:investmentOfferId` **Rest Request Parameters** The `respondToInvestmentOffer` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | investmentOfferId | ID | true | request.params?.["investmentOfferId"] | | offerAmount | Double | false | request.body?.["offerAmount"] | | message | Text | false | request.body?.["message"] | | status | Enum | false | request.body?.["status"] | | respondedAt | Date | false | request.body?.["respondedAt"] | | responseNote | Text | false | request.body?.["responseNote"] | **investmentOfferId** : This id paremeter is used to select the required data object that will be updated **offerAmount** : Investment amount in USD **message** : Cover letter or terms from the investor **status** : Offer lifecycle status **respondedAt** : When the project owner responded **responseNote** : Project owner note on accept/reject **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/respondtoinvestmentoffer/:investmentOfferId** ```js axios({ method: 'PATCH', url: `/v1/respondtoinvestmentoffer/${investmentOfferId}`, data: { offerAmount:"Double", message:"Text", status:"Enum", respondedAt:"Date", responseNote:"Text", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "investmentOffer", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "investmentOffer": { "id": "ID", "projectId": "ID", "investorUserId": "ID", "offerAmount": "Double", "message": "Text", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "responseNote": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Investmentoffers` API **[Default list API]** — This is the designated default `list` API for the `investmentOffer` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List investment offers. Admins see all, investors see their own, filmmakers/studios see offers on their projects. **Rest Route** The `listInvestmentOffers` API REST controller can be triggered via the following route: `/v1/investmentoffers` **Rest Request Parameters** **Filter Parameters** The `listInvestmentOffers` api supports 4 optional filter parameters for filtering list results: **projectId** (`ID`): Film project receiving the investment offer - Single: `?projectId=` - Multiple: `?projectId=&projectId=` - Null: `?projectId=null` **investorUserId** (`ID`): Investor who made the offer - Single: `?investorUserId=` - Multiple: `?investorUserId=&investorUserId=` - Null: `?investorUserId=null` **offerAmount** (`Double`): Investment amount in USD - Single: `?offerAmount=` - Multiple: `?offerAmount=&offerAmount=` - Range: `?offerAmount=$lt-`, `$lte-`, `$gt-`, `$gte-`, `$btw--` - Null: `?offerAmount=null` **status** (`Enum`): Offer lifecycle 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/investmentoffers** ```js axios({ method: 'GET', url: '/v1/investmentoffers', data: { }, params: { // Filter parameters (see Filter Parameters section above) // projectId: '' // Filter by projectId // investorUserId: '' // Filter by investorUserId // offerAmount: '' // Filter by offerAmount // 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": "investmentOffers", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "investmentOffers": [ { "id": "ID", "projectId": "ID", "investorUserId": "ID", "offerAmount": "Double", "message": "Text", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "responseNote": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Withdraw Investmentoffer` API Investor withdraws their own pending offer. Sets status to withdrawn. **Rest Route** The `withdrawInvestmentOffer` API REST controller can be triggered via the following route: `/v1/withdrawinvestmentoffer/:investmentOfferId` **Rest Request Parameters** The `withdrawInvestmentOffer` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | investmentOfferId | ID | true | request.params?.["investmentOfferId"] | | offerAmount | Double | false | request.body?.["offerAmount"] | | message | Text | false | request.body?.["message"] | | status | Enum | false | request.body?.["status"] | | respondedAt | Date | false | request.body?.["respondedAt"] | | responseNote | Text | false | request.body?.["responseNote"] | **investmentOfferId** : This id paremeter is used to select the required data object that will be updated **offerAmount** : Investment amount in USD **message** : Cover letter or terms from the investor **status** : Offer lifecycle status **respondedAt** : When the project owner responded **responseNote** : Project owner note on accept/reject **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/withdrawinvestmentoffer/:investmentOfferId** ```js axios({ method: 'PATCH', url: `/v1/withdrawinvestmentoffer/${investmentOfferId}`, data: { offerAmount:"Double", message:"Text", status:"Enum", respondedAt:"Date", responseNote:"Text", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "investmentOffer", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "investmentOffer": { "id": "ID", "projectId": "ID", "investorUserId": "ID", "offerAmount": "Double", "message": "Text", "status": "Enum", "status_idx": "Integer", "respondedAt": "Date", "responseNote": "Text", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Follow User` API **[Default create API]** — This is the designated default `create` API for the `userFollow` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Follow a user. Creates a follow relationship between the session user and the target user. Duplicate follows are prevented by composite index. **Rest Route** The `followUser` API REST controller can be triggered via the following route: `/v1/followuser` **Rest Request Parameters** The `followUser` api has got 2 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | followingUserId | ID | true | request.body?.["followingUserId"] | | followedAt | Date | false | request.body?.["followedAt"] | **followingUserId** : The user being followed **followedAt** : When the follow relationship was created **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/followuser** ```js axios({ method: 'POST', url: '/v1/followuser', data: { followingUserId:"ID", followedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userFollow", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "userFollow": { "id": "ID", "followerUserId": "ID", "followingUserId": "ID", "followedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Unfollow User` API **[Default delete API]** — This is the designated default `delete` API for the `userFollow` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Unfollow a user. Removes the follow relationship. Only the follower (owner) can unfollow. **Rest Route** The `unfollowUser` API REST controller can be triggered via the following route: `/v1/unfollowuser/:userFollowId` **Rest Request Parameters** The `unfollowUser` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userFollowId | ID | true | request.params?.["userFollowId"] | **userFollowId** : 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/unfollowuser/:userFollowId** ```js axios({ method: 'DELETE', url: `/v1/unfollowuser/${userFollowId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userFollow", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "userFollow": { "id": "ID", "followerUserId": "ID", "followingUserId": "ID", "followedAt": "Date", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `List Userfollows` API **[Default list API]** — This is the designated default `list` API for the `userFollow` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List follow relationships. Filter by followerUserId to get who a user follows, or by followingUserId to get a user's followers. **Rest Route** The `listUserFollows` API REST controller can be triggered via the following route: `/v1/userfollows` **Rest Request Parameters** **Filter Parameters** The `listUserFollows` api supports 2 optional filter parameters for filtering list results: **followerUserId** (`ID`): The user who is following - Single: `?followerUserId=` - Multiple: `?followerUserId=&followerUserId=` - Null: `?followerUserId=null` **followingUserId** (`ID`): The user being followed - Single: `?followingUserId=` - Multiple: `?followingUserId=&followingUserId=` - Null: `?followingUserId=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/userfollows** ```js axios({ method: 'GET', url: '/v1/userfollows', data: { }, params: { // Filter parameters (see Filter Parameters section above) // followerUserId: '' // Filter by followerUserId // followingUserId: '' // Filter by followingUserId } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "userFollows", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "userFollows": [ { "id": "ID", "followerUserId": "ID", "followingUserId": "ID", "followedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - MessagingCenter Service** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of messagingCenter ## Service Access MessagingCenter service management is handled through service specific base urls. MessagingCenter service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the messagingCenter service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/messagingcenter-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/messagingcenter-api` * **Production:** `https://auteurlabb.mindbricks.co/messagingcenter-api` ## Scope **MessagingCenter Service Description** Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations. MessagingCenter service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`messageThread` Data Object**: A thread (private or group) representing a conversation among platform users, optionally linked to a film project **`message` Data Object**: A message sent in a thread between platform users, with moderation and delivery tracking. ## MessagingCenter Service Frontend Description By The Backend Architect - Enables direct and group messaging for filmmakers, studios, investors. Threads are enriched with last message data (for conversations list), and moderation status is reflected for flagged/removed content. - Users see only their own threads and messages unless admin. Admins see all for moderation and compliance. - Each message is linked to a thread; project context is attached for film/discussion linkage. - Last message, read receipts, and moderation status are available in the messaging UI for full state handling. Subject field required for group/archived threads; otherwise, for two-person threads subject is optional. - Non-admin users can only modify their own messages (within an edit window); only admins can change flagged/moderation states. - Notification events for new messages/threads drive in-app notifications and badges. - Flag/report message flows may link to a moderation UI for admin action. Standard message flows follow real-time or poll-based updates as orchestrated by frontend. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## MessageThread Data Object A thread (private or group) representing a conversation among platform users, optionally linked to a film project ### MessageThread Data Object Frontend Description By The Backend Architect Represents the context for a conversation (one-on-one or group) among users. Subject is displayed for group/archived/flagged threads; threads can be listed by participant for chat list UI; relatedProjectId links the thread to a film project for context. Threads can be archived, flagged, or active. ### MessageThread Data Object Properties MessageThread data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `participantIds` | ID | true | Yes | No | IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1) | | `subject` | String | false | No | No | Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty. | | `relatedProjectId` | ID | false | No | No | (Optional) The project this thread is about. | | `isGroup` | Boolean | false | Yes | No | True if thread is a group chat, false if private 1-to-1 message. | | `createdBy` | ID | false | Yes | No | User who created the thread. | | `lastMessageAt` | Date | false | Yes | No | Timestamp of the last message in this thread (used for sorting). | | `threadStatus` | Enum | false | Yes | No | Status of the thread: active, archived, flagged. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Array Properties `participantIds` Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **threadStatus**: [active, archived, flagged] ### Relation Properties `participantIds` `relatedProjectId` `createdBy` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **participantIds**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **relatedProjectId**: ID Relation to `filmProject`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No - **createdBy**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ### Filter Properties `participantIds` `relatedProjectId` `threadStatus` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **participantIds**: ID has a filter named `participantId` - **relatedProjectId**: ID has a filter named `relatedProjectId` - **threadStatus**: Enum has a filter named `threadStatus` ## Message Data Object A message sent in a thread between platform users, with moderation and delivery tracking. ### Message Data Object Frontend Description By The Backend Architect Represents a participant's sent message in a conversation. Each message is linked to a thread, contains sender/recipient data, the message content, sent and read dates, and moderation status (normal, flagged, removed). Only the sender can edit (if not flagged/removed and within a grace period), only admin can set moderation actions (for platform safety). Used for chat/message UIs, moderation/inbox displays. ### Message Data Object Properties Message data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `threadId` | ID | false | Yes | No | The parent thread of this message. | | `senderId` | ID | false | Yes | No | User ID of the sender. | | `content` | Text | false | Yes | No | The actual message content (body). | | `sentAt` | Date | false | Yes | No | When the message was sent. | | `readByIds` | ID | true | No | No | User IDs who have read the message (for read receipts). | | `moderationStatus` | Enum | false | Yes | No | Moderation status: normal (default), flagged (pending review), or removed by admin/moderation. | | `flaggedReason` | String | false | No | No | Reason for message being flagged (set by admin or reporting workflow). | | `adminAction` | String | false | No | No | Admin/moderator action/note taken regarding this message (set only by admin). | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Array Properties `readByIds` Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **moderationStatus**: [normal, flagged, removed] ### Relation Properties `threadId` `senderId` `readByIds` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **threadId**: ID Relation to `messageThread`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **senderId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **readByIds**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `threadId` `moderationStatus` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **threadId**: ID has a filter named `threadId` - **moderationStatus**: Enum has a filter named `moderationStatus` ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### MessageThread Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createMessageThread` | `/v1/messagethreads` | Yes | | Update | `updateMessageThread` | `/v1/messagethreads/:messageThreadId` | Yes | | Delete | _none_ | - | Auto | | Get | `getMessageThread` | `/v1/messagethreads/:messageThreadId` | Yes | | List | `listMessageThreads` | `/v1/messagethreads` | Yes | ### Message Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createMessage` | `/v1/messages` | Yes | | Update | `updateMessage` | `/v1/messages/:messageId` | Yes | | Delete | `deleteMessage` | `/v1/messages/:messageId` | Yes | | Get | `getMessage` | `/v1/messages/:messageId` | Yes | | List | `listMessages` | `/v1/messages` | Yes | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Create Messagethread` API **[Default create API]** — This is the designated default `create` API for the `messageThread` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new message thread (private or group). Can optionally link to a film project. Enforces participants count and role access. **API Frontend Description By The Backend Architect** For users to start a new conversation (private or group chat) with one or more participants (including themselves); optionally link the thread to a project, set subject (required for group/flagged threads only), subject can be empty for 1-to-1; lastMessageAt auto-set to creation time. **Rest Route** The `createMessageThread` API REST controller can be triggered via the following route: `/v1/messagethreads` **Rest Request Parameters** The `createMessageThread` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | participantIds | ID | true | request.body?.["participantIds"] | | subject | String | false | request.body?.["subject"] | | relatedProjectId | ID | false | request.body?.["relatedProjectId"] | | isGroup | Boolean | true | request.body?.["isGroup"] | | lastMessageAt | Date | true | request.body?.["lastMessageAt"] | | threadStatus | Enum | true | request.body?.["threadStatus"] | **participantIds** : IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1) **subject** : Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty. **relatedProjectId** : (Optional) The project this thread is about. **isGroup** : True if thread is a group chat, false if private 1-to-1 message. **lastMessageAt** : Timestamp of the last message in this thread (used for sorting). **threadStatus** : Status of the thread: active, archived, flagged. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/messagethreads** ```js axios({ method: 'POST', url: '/v1/messagethreads', data: { participantIds:"ID", subject:"String", relatedProjectId:"ID", isGroup:"Boolean", lastMessageAt:"Date", threadStatus:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "messageThread", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "messageThread": { "id": "ID", "participantIds": "ID", "subject": "String", "relatedProjectId": "ID", "isGroup": "Boolean", "createdBy": "ID", "lastMessageAt": "Date", "threadStatus": "Enum", "threadStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "lastMessage": [ { "senderId": "ID", "content": "Text", "sentAt": "Date", "moderationStatus": "Enum", "moderationStatus_idx": "Integer" }, {}, {} ], "relatedProject": { "title": "String", "projectType": "Enum", "projectType_idx": "Integer", "ownerUserId": "ID", "isPublic": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer" } } } ``` ### `Get Messagethread` API **[Default get API]** — This is the designated default `get` API for the `messageThread` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a message thread and last message; only participants or admin may retrieve. **API Frontend Description By The Backend Architect** For thread detail/conversation load: returns thread and its related context (last message, project info). Enforces access: only participants and admins. **Rest Route** The `getMessageThread` API REST controller can be triggered via the following route: `/v1/messagethreads/:messageThreadId` **Rest Request Parameters** The `getMessageThread` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageThreadId | ID | true | request.params?.["messageThreadId"] | **messageThreadId** : 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/messagethreads/:messageThreadId** ```js axios({ method: 'GET', url: `/v1/messagethreads/${messageThreadId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "messageThread", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "messageThread": { "id": "ID", "participantIds": "ID", "subject": "String", "relatedProjectId": "ID", "isGroup": "Boolean", "createdBy": "ID", "lastMessageAt": "Date", "threadStatus": "Enum", "threadStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "lastMessage": [ { "senderId": "ID", "content": "Text", "sentAt": "Date", "moderationStatus": "Enum", "moderationStatus_idx": "Integer" }, {}, {} ], "relatedProject": { "title": "String", "projectType": "Enum", "projectType_idx": "Integer", "ownerUserId": "ID", "isPublic": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer" } } } ``` ### `List Messagethreads` API **[Default list API]** — This is the designated default `list` API for the `messageThread` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List threads for current user (participantIds contains session userId), or all threads for admin. Filters: by project, thread status, participant, search by subject. Sorted by lastMessageAt desc. **API Frontend Description By The Backend Architect** Returns conversation list for chat inbox. By default lists threads where session user is a participant, with last message for display. Admins can filter/status for moderation, filter by related project for context. Supports pagination. **Rest Route** The `listMessageThreads` API REST controller can be triggered via the following route: `/v1/messagethreads` **Rest Request Parameters** **Filter Parameters** The `listMessageThreads` api supports 4 optional filter parameters for filtering list results: **participantId** (`ID` array): IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1) - Single: `?participantId=` - Multiple: `?participantId=&participantId=` - Null: `?participantId=null` - Array contains: `?participantId=&participantId_op=contains` (default) - Array overlap: `?participantId=&participantId=&participantId_op=overlap` **participantId_op** (`String`): Operator for filtering array property "participantIds". Use "contains" to check if array contains the value, or "overlap" to check if arrays have common elements. - Single (partial match, case-insensitive): `?participantId_op=` - Multiple: `?participantId_op=&participantId_op=` - Null: `?participantId_op=null` **relatedProjectId** (`ID`): (Optional) The project this thread is about. - Single: `?relatedProjectId=` - Multiple: `?relatedProjectId=&relatedProjectId=` - Null: `?relatedProjectId=null` **threadStatus** (`Enum`): Status of the thread: active, archived, flagged. - Single: `?threadStatus=` (case-insensitive) - Multiple: `?threadStatus=&threadStatus=` - Null: `?threadStatus=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/messagethreads** ```js axios({ method: 'GET', url: '/v1/messagethreads', data: { }, params: { // Filter parameters (see Filter Parameters section above) // participantId: '' // Filter by participantId // participantId_op: '' // Filter by participantId_op // relatedProjectId: '' // Filter by relatedProjectId // threadStatus: '' // Filter by threadStatus } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "messageThreads", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "messageThreads": [ { "id": "ID", "participantIds": "ID", "subject": "String", "relatedProjectId": "ID", "isGroup": "Boolean", "createdBy": "ID", "lastMessageAt": "Date", "threadStatus": "Enum", "threadStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "lastMessage": [ { "senderId": "ID", "content": "Text", "sentAt": "Date", "moderationStatus": "Enum", "moderationStatus_idx": "Integer" }, {}, {} ], "relatedProject": [ { "title": "String", "projectType": "Enum", "projectType_idx": "Integer", "ownerUserId": "ID", "isPublic": "Boolean", "approvalStatus": "Enum", "approvalStatus_idx": "Integer" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Messagethread` API **[Default update API]** — This is the designated default `update` API for the `messageThread` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update thread (subject, status, participants for group). Only thread creator, participants (for subject/archival), or admin can update. Only admin can set status=flagged. **API Frontend Description By The Backend Architect** Allows editing of thread subject, status (archival/flag for moderation), or for admin actions; participants cannot update thread participants unless admin/group owner. All updates are logged for audit. Only admin may set flagged status. **Rest Route** The `updateMessageThread` API REST controller can be triggered via the following route: `/v1/messagethreads/:messageThreadId` **Rest Request Parameters** The `updateMessageThread` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageThreadId | ID | true | request.params?.["messageThreadId"] | | participantIds | ID | false | request.body?.["participantIds"] | | subject | String | false | request.body?.["subject"] | | relatedProjectId | ID | false | request.body?.["relatedProjectId"] | | isGroup | Boolean | false | request.body?.["isGroup"] | | lastMessageAt | Date | false | request.body?.["lastMessageAt"] | | threadStatus | Enum | false | request.body?.["threadStatus"] | **messageThreadId** : This id paremeter is used to select the required data object that will be updated **participantIds** : IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1) **subject** : Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty. **relatedProjectId** : (Optional) The project this thread is about. **isGroup** : True if thread is a group chat, false if private 1-to-1 message. **lastMessageAt** : Timestamp of the last message in this thread (used for sorting). **threadStatus** : Status of the thread: active, archived, flagged. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/messagethreads/:messageThreadId** ```js axios({ method: 'PATCH', url: `/v1/messagethreads/${messageThreadId}`, data: { participantIds:"ID", subject:"String", relatedProjectId:"ID", isGroup:"Boolean", lastMessageAt:"Date", threadStatus:"Enum", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "messageThread", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "messageThread": { "id": "ID", "participantIds": "ID", "subject": "String", "relatedProjectId": "ID", "isGroup": "Boolean", "createdBy": "ID", "lastMessageAt": "Date", "threadStatus": "Enum", "threadStatus_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Create Message` API **[Default create API]** — This is the designated default `create` API for the `message` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send a message (post) in a thread. Only thread participants allowed. Thread lastMessageAt is updated. **API Frontend Description By The Backend Architect** Sends a message in an existing conversation (thread). Access check: only participants may send. Sets senderId, sentAt. Notifies via events. Supports message content, moderation default = normal. Marks thread lastMessageAt for inbox sort. **Rest Route** The `createMessage` API REST controller can be triggered via the following route: `/v1/messages` **Rest Request Parameters** The `createMessage` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | threadId | ID | true | request.body?.["threadId"] | | content | Text | true | request.body?.["content"] | | readByIds | ID | false | request.body?.["readByIds"] | | moderationStatus | Enum | true | request.body?.["moderationStatus"] | | flaggedReason | String | false | request.body?.["flaggedReason"] | | adminAction | String | false | request.body?.["adminAction"] | **threadId** : The parent thread of this message. **content** : The actual message content (body). **readByIds** : User IDs who have read the message (for read receipts). **moderationStatus** : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation. **flaggedReason** : Reason for message being flagged (set by admin or reporting workflow). **adminAction** : Admin/moderator action/note taken regarding this message (set only by admin). **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/messages** ```js axios({ method: 'POST', url: '/v1/messages', data: { threadId:"ID", content:"Text", readByIds:"ID", moderationStatus:"Enum", flaggedReason:"String", adminAction:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "threadId": "ID", "senderId": "ID", "content": "Text", "sentAt": "Date", "readByIds": "ID", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "flaggedReason": "String", "adminAction": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Message` API **[Default get API]** — This is the designated default `get` API for the `message` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single message, thread participant or admin only. **API Frontend Description By The Backend Architect** Load message (for thread/conversation display or moderation). Only allowed for participant or admin/superAdmin. **Rest Route** The `getMessage` API REST controller can be triggered via the following route: `/v1/messages/:messageId` **Rest Request Parameters** The `getMessage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageId | ID | true | request.params?.["messageId"] | **messageId** : 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/messages/:messageId** ```js axios({ method: 'GET', url: `/v1/messages/${messageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "threadId": "ID", "senderId": "ID", "content": "Text", "sentAt": "Date", "readByIds": "ID", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "flaggedReason": "String", "adminAction": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "thread": { "participantIds": "ID", "subject": "String", "relatedProjectId": "ID", "threadStatus": "Enum", "threadStatus_idx": "Integer" } } } ``` ### `List Messages` API **[Default list API]** — This is the designated default `list` API for the `message` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages for a thread (or per filter by participant/project/moderation). Participant or admin only. **API Frontend Description By The Backend Architect** Conversation message list for a given thread, or admin-moderated message audit. Enables filter/sort/paginate (newest last). Only participant of the thread or admin can list. **Rest Route** The `listMessages` API REST controller can be triggered via the following route: `/v1/messages` **Rest Request Parameters** **Filter Parameters** The `listMessages` api supports 2 optional filter parameters for filtering list results: **threadId** (`ID`): The parent thread of this message. - Single: `?threadId=` - Multiple: `?threadId=&threadId=` - Null: `?threadId=null` **moderationStatus** (`Enum`): Moderation status: normal (default), flagged (pending review), or removed by admin/moderation. - Single: `?moderationStatus=` (case-insensitive) - Multiple: `?moderationStatus=&moderationStatus=` - Null: `?moderationStatus=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/messages** ```js axios({ method: 'GET', url: '/v1/messages', data: { }, params: { // Filter parameters (see Filter Parameters section above) // threadId: '' // Filter by threadId // moderationStatus: '' // Filter by moderationStatus } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "messages", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "messages": [ { "id": "ID", "threadId": "ID", "senderId": "ID", "content": "Text", "sentAt": "Date", "readByIds": "ID", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "flaggedReason": "String", "adminAction": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "thread": [ { "participantIds": "ID", "subject": "String", "relatedProjectId": "ID", "threadStatus": "Enum", "threadStatus_idx": "Integer" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Message` API **[Default update API]** — This is the designated default `update` API for the `message` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a message's content (by sender & only before flagged/removed) or moderation fields (admin only). **API Frontend Description By The Backend Architect** Sender may edit own message content if not yet flagged/removed and within allowed time window (if desired). Only admin may set moderationStatus, flaggedReason, adminAction fields. **Rest Route** The `updateMessage` API REST controller can be triggered via the following route: `/v1/messages/:messageId` **Rest Request Parameters** The `updateMessage` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageId | ID | true | request.params?.["messageId"] | | content | Text | false | request.body?.["content"] | | readByIds | ID | false | request.body?.["readByIds"] | | moderationStatus | Enum | false | request.body?.["moderationStatus"] | | flaggedReason | String | false | request.body?.["flaggedReason"] | | adminAction | String | false | request.body?.["adminAction"] | **messageId** : This id paremeter is used to select the required data object that will be updated **content** : The actual message content (body). **readByIds** : User IDs who have read the message (for read receipts). **moderationStatus** : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation. **flaggedReason** : Reason for message being flagged (set by admin or reporting workflow). **adminAction** : Admin/moderator action/note taken regarding this message (set only by admin). **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/messages/:messageId** ```js axios({ method: 'PATCH', url: `/v1/messages/${messageId}`, data: { content:"Text", readByIds:"ID", moderationStatus:"Enum", flaggedReason:"String", adminAction:"String", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "threadId": "ID", "senderId": "ID", "content": "Text", "sentAt": "Date", "readByIds": "ID", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "flaggedReason": "String", "adminAction": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Delete Message` API **[Default delete API]** — This is the designated default `delete` API for the `message` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete message (by sender - if unflagged, or admin at any time). **API Frontend Description By The Backend Architect** Sender may remove their own unflagged/unmoderated message; admin may remove (hard/soft) any message (for moderation cleanup). All deletes are soft by default (isActive=false). **Rest Route** The `deleteMessage` API REST controller can be triggered via the following route: `/v1/messages/:messageId` **Rest Request Parameters** The `deleteMessage` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | messageId | ID | true | request.params?.["messageId"] | **messageId** : 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/messages/:messageId** ```js axios({ method: 'DELETE', url: `/v1/messages/${messageId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "message", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "message": { "id": "ID", "threadId": "ID", "senderId": "ID", "content": "Text", "sentAt": "Date", "readByIds": "ID", "moderationStatus": "Enum", "moderationStatus_idx": "Integer", "flaggedReason": "String", "adminAction": "String", "isActive": false, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - ModerationAdmin Service** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of moderationAdmin ## Service Access ModerationAdmin service management is handled through service specific base urls. ModerationAdmin service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the moderationAdmin service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/moderationadmin-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/moderationadmin-api` * **Production:** `https://auteurlabb.mindbricks.co/moderationadmin-api` ## Scope **ModerationAdmin Service Description** Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance. ModerationAdmin service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`approvalRequest` Data Object**: Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin. **`reportLog` Data Object**: Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info. **`suspensionRecord` Data Object**: Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance. **`auditLog` Data Object**: Generic audit log for all admin/moderation actions across services/objects for compliance and traceability. ## ModerationAdmin Service Frontend Description By The Backend Architect This service is not user-facing and is used strictly for admin and moderation workflows. Typical frontend behaviors involve presenting lists of pending approvals, moderation reports, and audit logs to admins, allowing them to perform workflow actions and review logs. End users can see the status of their own approval requests and reports only. All actions are strictly role-gated. There are no public endpoints. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## ApprovalRequest Data Object Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin. ### ApprovalRequest Data Object Frontend Description By The Backend Architect Admins are shown lists of pending, approved, or rejected requests. Only admins can approve/reject; creators can view their own request status but not others. Status and review notes are shown to creators only after decision. All changes are audit-logged. ### ApprovalRequest Data Object Properties ApprovalRequest data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `targetType` | Enum | false | Yes | No | Type of entity being approved (studio, investor, project) | | `targetId` | ID | false | Yes | No | ID of entity being approved (user or project, depending on type) | | `requestedAt` | Date | false | Yes | No | Request creation time | | `requestedByUserId` | ID | false | Yes | No | User ID who created the request | | `status` | Enum | false | Yes | No | Approval status: pending/approved/rejected | | `reviewedAt` | Date | false | No | No | Date/time request reviewed | | `reviewedByUserId` | ID | false | No | No | Admin userId who reviewed the request | | `adminNote` | String | false | No | No | Review note left by admin. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **targetType**: [studio, investor, project, filmmaker] - **status**: [pending, approved, rejected] ### Relation Properties `requestedByUserId` `reviewedByUserId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **requestedByUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **reviewedByUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `targetType` `targetId` `status` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **targetType**: Enum has a filter named `targetType` - **targetId**: ID has a filter named `targetId` - **status**: Enum has a filter named `status` ## ReportLog Data Object Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info. ### ReportLog Data Object Frontend Description By The Backend Architect Admins are shown lists of open/closed/ignored reports and take action by marking as reviewed, adding action notes. Reporting users can see their own report status. All logs reference the original content by type and ID. ### ReportLog Data Object Properties ReportLog data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `contentType` | Enum | false | Yes | No | Type of content being reported: project/message/user | | `contentId` | ID | false | Yes | No | ID of the reported content (project ID, message ID, user ID) | | `reportType` | String | false | Yes | No | Nature of report (abuse, spam, copyright, etc.) | | `reportedByUserId` | ID | false | Yes | No | ID of user reporting | | `reportedAt` | Date | false | Yes | No | Report creation timestamp | | `reviewStatus` | Enum | false | Yes | No | Open/closed/ignored | | `reviewAction` | String | false | No | No | Action taken by admin (removed, warned, etc.) or note | | `actionedByUserId` | ID | false | No | No | Admin making the moderation action | | `actionedAt` | Date | false | No | No | Time of moderation action | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **contentType**: [project, message, user] - **reviewStatus**: [open, closed, ignored] ### Relation Properties `reportedByUserId` `actionedByUserId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **reportedByUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **actionedByUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: No ### Filter Properties `contentType` `contentId` `reportType` `reviewStatus` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **contentType**: Enum has a filter named `contentType` - **contentId**: ID has a filter named `contentId` - **reportType**: String has a filter named `reportType` - **reviewStatus**: Enum has a filter named `reviewStatus` ## SuspensionRecord Data Object Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance. ### SuspensionRecord Data Object Frontend Description By The Backend Architect Admins may suspend or reinstate users for violation of policies. Each action is logged; suspension status controls actual access (isActive in core user record). Only admins may create suspension records. All changes update the core auth:user record (isActive). ### SuspensionRecord Data Object Properties SuspensionRecord data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `userId` | ID | false | Yes | No | Suspended user id | | `reason` | String | false | Yes | No | Reason for suspension action | | `suspendedByUserId` | ID | false | Yes | No | Admin ID who performed the suspension action | | `suspendedAt` | Date | false | Yes | No | Time of action (suspend/lift) | | `status` | Enum | false | Yes | No | Current state: active (suspended), lifted (reinstated) | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **status**: [active, lifted] ### Relation Properties `userId` `suspendedByUserId` Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one. In frontend, please ensure that, 1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field. - **userId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes - **suspendedByUserId**: ID Relation to `user`.id The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object. Required: Yes ## AuditLog Data Object Generic audit log for all admin/moderation actions across services/objects for compliance and traceability. ### AuditLog Data Object Frontend Description By The Backend Architect Admins/reviewers can list or view audit log entries. All log entries are immutable and trace detailed actions for compliance. No updates or deletions allowed. ### AuditLog Data Object Properties AuditLog data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `actionType` | String | false | Yes | No | Type of admin action (created, updated, suspended, approved, etc.) | | `actorUserId` | ID | false | Yes | No | User ID of admin/staff performing the action | | `targetType` | String | false | Yes | No | Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.) | | `targetId` | ID | false | Yes | No | ID of the object affected by this action | | `details` | Text | false | No | No | Freeform details, note, or JSON blob describing action context | | `actionAt` | Date | false | Yes | No | When the action occurred | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### ApprovalRequest Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createApprovalRequest` | `/v1/approvalrequests` | Yes | | Update | `reviewApprovalRequest` | `/v1/reviewapprovalrequest/:approvalRequestId` | Yes | | Delete | _none_ | - | Auto | | Get | `getApprovalRequest` | `/v1/approvalrequests/:approvalRequestId` | Yes | | List | `listApprovalRequests` | `/v1/approvalrequests` | Yes | ### ReportLog Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createReportLog` | `/v1/reportlogs` | Yes | | Update | `reviewReportLog` | `/v1/reviewreportlog/:reportLogId` | Yes | | Delete | _none_ | - | Auto | | Get | `getReportLog` | `/v1/reportlogs/:reportLogId` | Yes | | List | `listReportLogs` | `/v1/reportlogs` | Yes | ### SuspensionRecord Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createSuspensionRecord` | `/v1/suspensionrecords` | Yes | | Update | `liftSuspensionRecord` | `/v1/liftsuspensionrecord/:suspensionRecordId` | Yes | | Delete | _none_ | - | Auto | | Get | `getSuspensionRecord` | `/v1/suspensionrecords/:suspensionRecordId` | Yes | | List | `listSuspensionRecords` | `/v1/suspensionrecords` | Yes | ### AuditLog Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAuditLog` | `/v1/auditlogs` | Yes | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getAuditLog` | `/v1/auditlogs/:auditLogId` | Yes | | List | `listAuditLogs` | `/v1/auditlogs` | Yes | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Create Approvalrequest` API **[Default create API]** — This is the designated default `create` API for the `approvalRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new approval request for studio, investor, or project. Status defaults to pending. Only non-admins can create requests for themselvessss. **Rest Route** The `createApprovalRequest` API REST controller can be triggered via the following route: `/v1/approvalrequests` **Rest Request Parameters** The `createApprovalRequest` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | targetType | Enum | true | request.body?.["targetType"] | | targetId | ID | true | request.body?.["targetId"] | | requestedAt | Date | true | request.body?.["requestedAt"] | | reviewedAt | Date | false | request.body?.["reviewedAt"] | | reviewedByUserId | ID | false | request.body?.["reviewedByUserId"] | | adminNote | String | false | request.body?.["adminNote"] | **targetType** : Type of entity being approved (studio, investor, project) **targetId** : ID of entity being approved (user or project, depending on type) **requestedAt** : Request creation time **reviewedAt** : Date/time request reviewed **reviewedByUserId** : Admin userId who reviewed the request **adminNote** : Review note left by admin. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/approvalrequests** ```js axios({ method: 'POST', url: '/v1/approvalrequests', data: { targetType:"Enum", targetId:"ID", requestedAt:"Date", reviewedAt:"Date", reviewedByUserId:"ID", 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": "approvalRequest", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "approvalRequest": { "id": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "requestedAt": "Date", "requestedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "reviewedAt": "Date", "reviewedByUserId": "ID", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Review Approvalrequest` API **[Default update API]** — This is the designated default `update` API for the `approvalRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Approve or reject an approval request. Only superAdmin or admin may update status or add review notes. **Rest Route** The `reviewApprovalRequest` API REST controller can be triggered via the following route: `/v1/reviewapprovalrequest/:approvalRequestId` **Rest Request Parameters** The `reviewApprovalRequest` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | approvalRequestId | ID | true | request.params?.["approvalRequestId"] | | status | Enum | true | request.body?.["status"] | | reviewedAt | Date | false | request.body?.["reviewedAt"] | | reviewedByUserId | ID | false | request.body?.["reviewedByUserId"] | | adminNote | String | false | request.body?.["adminNote"] | **approvalRequestId** : This id paremeter is used to select the required data object that will be updated **status** : Approval status: pending/approved/rejected **reviewedAt** : Date/time request reviewed **reviewedByUserId** : Admin userId who reviewed the request **adminNote** : Review note left by admin. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/reviewapprovalrequest/:approvalRequestId** ```js axios({ method: 'PATCH', url: `/v1/reviewapprovalrequest/${approvalRequestId}`, data: { status:"Enum", reviewedAt:"Date", reviewedByUserId:"ID", 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": "approvalRequest", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "approvalRequest": { "id": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "requestedAt": "Date", "requestedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "reviewedAt": "Date", "reviewedByUserId": "ID", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Approvalrequest` API **[Default get API]** — This is the designated default `get` API for the `approvalRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single approvalRequest. Only owner or admin may view. **Rest Route** The `getApprovalRequest` API REST controller can be triggered via the following route: `/v1/approvalrequests/:approvalRequestId` **Rest Request Parameters** The `getApprovalRequest` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | approvalRequestId | ID | true | request.params?.["approvalRequestId"] | **approvalRequestId** : 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/approvalrequests/:approvalRequestId** ```js axios({ method: 'GET', url: `/v1/approvalrequests/${approvalRequestId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "approvalRequest", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "approvalRequest": { "id": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "requestedAt": "Date", "requestedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "reviewedAt": "Date", "reviewedByUserId": "ID", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "requester": { "email": "String", "fullname": "String", "roleId": "String" }, "reviewer": { "email": "String", "fullname": "String" } } } ``` ### `List Approvalrequests` API **[Default list API]** — This is the designated default `list` API for the `approvalRequest` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List approval requests. Admins see all, non-admins see only their own. **Rest Route** The `listApprovalRequests` API REST controller can be triggered via the following route: `/v1/approvalrequests` **Rest Request Parameters** **Filter Parameters** The `listApprovalRequests` api supports 3 optional filter parameters for filtering list results: **targetType** (`Enum`): Type of entity being approved (studio, investor, project) - Single: `?targetType=` (case-insensitive) - Multiple: `?targetType=&targetType=` - Null: `?targetType=null` **targetId** (`ID`): ID of entity being approved (user or project, depending on type) - Single: `?targetId=` - Multiple: `?targetId=&targetId=` - Null: `?targetId=null` **status** (`Enum`): Approval status: pending/approved/rejected - 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/approvalrequests** ```js axios({ method: 'GET', url: '/v1/approvalrequests', data: { }, params: { // Filter parameters (see Filter Parameters section above) // targetType: '' // Filter by targetType // targetId: '' // Filter by targetId // 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": "approvalRequests", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "approvalRequests": [ { "id": "ID", "targetType": "Enum", "targetType_idx": "Integer", "targetId": "ID", "requestedAt": "Date", "requestedByUserId": "ID", "status": "Enum", "status_idx": "Integer", "reviewedAt": "Date", "reviewedByUserId": "ID", "adminNote": "String", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "requester": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "reviewer": [ { "email": "String", "fullname": "String" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Reportlog` API **[Default create API]** — This is the designated default `create` API for the `reportLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a content/user/project moderation report **Rest Route** The `createReportLog` API REST controller can be triggered via the following route: `/v1/reportlogs` **Rest Request Parameters** The `createReportLog` api has got 7 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | contentType | Enum | true | request.body?.["contentType"] | | contentId | ID | true | request.body?.["contentId"] | | reportType | String | true | request.body?.["reportType"] | | reportedAt | Date | true | request.body?.["reportedAt"] | | reviewAction | String | false | request.body?.["reviewAction"] | | actionedByUserId | ID | false | request.body?.["actionedByUserId"] | | actionedAt | Date | false | request.body?.["actionedAt"] | **contentType** : Type of content being reported: project/message/user **contentId** : ID of the reported content (project ID, message ID, user ID) **reportType** : Nature of report (abuse, spam, copyright, etc.) **reportedAt** : Report creation timestamp **reviewAction** : Action taken by admin (removed, warned, etc.) or note **actionedByUserId** : Admin making the moderation action **actionedAt** : Time of moderation action **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/reportlogs** ```js axios({ method: 'POST', url: '/v1/reportlogs', data: { contentType:"Enum", contentId:"ID", reportType:"String", reportedAt:"Date", reviewAction:"String", actionedByUserId:"ID", actionedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "reportLog", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "reportLog": { "id": "ID", "contentType": "Enum", "contentType_idx": "Integer", "contentId": "ID", "reportType": "String", "reportedByUserId": "ID", "reportedAt": "Date", "reviewStatus": "Enum", "reviewStatus_idx": "Integer", "reviewAction": "String", "actionedByUserId": "ID", "actionedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Review Reportlog` API **[Default update API]** — This is the designated default `update` API for the `reportLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin-only: Close/ignore a report, add review action/note. Only superAdmin/admin allowed. **Rest Route** The `reviewReportLog` API REST controller can be triggered via the following route: `/v1/reviewreportlog/:reportLogId` **Rest Request Parameters** The `reviewReportLog` api has got 5 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportLogId | ID | true | request.params?.["reportLogId"] | | reviewStatus | Enum | true | request.body?.["reviewStatus"] | | reviewAction | String | false | request.body?.["reviewAction"] | | actionedByUserId | ID | false | request.body?.["actionedByUserId"] | | actionedAt | Date | false | request.body?.["actionedAt"] | **reportLogId** : This id paremeter is used to select the required data object that will be updated **reviewStatus** : Open/closed/ignored **reviewAction** : Action taken by admin (removed, warned, etc.) or note **actionedByUserId** : Admin making the moderation action **actionedAt** : Time of moderation action **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/reviewreportlog/:reportLogId** ```js axios({ method: 'PATCH', url: `/v1/reviewreportlog/${reportLogId}`, data: { reviewStatus:"Enum", reviewAction:"String", actionedByUserId:"ID", actionedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "reportLog", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "reportLog": { "id": "ID", "contentType": "Enum", "contentType_idx": "Integer", "contentId": "ID", "reportType": "String", "reportedByUserId": "ID", "reportedAt": "Date", "reviewStatus": "Enum", "reviewStatus_idx": "Integer", "reviewAction": "String", "actionedByUserId": "ID", "actionedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Reportlog` API **[Default get API]** — This is the designated default `get` API for the `reportLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single report log. Only admins or reporting user may view. **Rest Route** The `getReportLog` API REST controller can be triggered via the following route: `/v1/reportlogs/:reportLogId` **Rest Request Parameters** The `getReportLog` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | reportLogId | ID | true | request.params?.["reportLogId"] | **reportLogId** : 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/reportlogs/:reportLogId** ```js axios({ method: 'GET', url: `/v1/reportlogs/${reportLogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "reportLog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "reportLog": { "id": "ID", "contentType": "Enum", "contentType_idx": "Integer", "contentId": "ID", "reportType": "String", "reportedByUserId": "ID", "reportedAt": "Date", "reviewStatus": "Enum", "reviewStatus_idx": "Integer", "reviewAction": "String", "actionedByUserId": "ID", "actionedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "reportedBy": { "email": "String", "fullname": "String", "roleId": "String" }, "actionedBy": { "email": "String", "fullname": "String" } } } ``` ### `List Reportlogs` API **[Default list API]** — This is the designated default `list` API for the `reportLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moderation reports. Admins see all; other users see only their reports. **Rest Route** The `listReportLogs` API REST controller can be triggered via the following route: `/v1/reportlogs` **Rest Request Parameters** **Filter Parameters** The `listReportLogs` api supports 4 optional filter parameters for filtering list results: **contentType** (`Enum`): Type of content being reported: project/message/user - Single: `?contentType=` (case-insensitive) - Multiple: `?contentType=&contentType=` - Null: `?contentType=null` **contentId** (`ID`): ID of the reported content (project ID, message ID, user ID) - Single: `?contentId=` - Multiple: `?contentId=&contentId=` - Null: `?contentId=null` **reportType** (`String`): Nature of report (abuse, spam, copyright, etc.) - Single (partial match, case-insensitive): `?reportType=` - Multiple: `?reportType=&reportType=` - Null: `?reportType=null` **reviewStatus** (`Enum`): Open/closed/ignored - Single: `?reviewStatus=` (case-insensitive) - Multiple: `?reviewStatus=&reviewStatus=` - Null: `?reviewStatus=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/reportlogs** ```js axios({ method: 'GET', url: '/v1/reportlogs', data: { }, params: { // Filter parameters (see Filter Parameters section above) // contentType: '' // Filter by contentType // contentId: '' // Filter by contentId // reportType: '' // Filter by reportType // reviewStatus: '' // Filter by reviewStatus } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "reportLogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "reportLogs": [ { "id": "ID", "contentType": "Enum", "contentType_idx": "Integer", "contentId": "ID", "reportType": "String", "reportedByUserId": "ID", "reportedAt": "Date", "reviewStatus": "Enum", "reviewStatus_idx": "Integer", "reviewAction": "String", "actionedByUserId": "ID", "actionedAt": "Date", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "reportedBy": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "actionedBy": [ { "email": "String", "fullname": "String" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Suspensionrecord` API **[Default create API]** — This is the designated default `create` API for the `suspensionRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin: suspend a user from the platform. Action triggers update to auth:user isActive = false. **Rest Route** The `createSuspensionRecord` API REST controller can be triggered via the following route: `/v1/suspensionrecords` **Rest Request Parameters** The `createSuspensionRecord` api has got 4 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | userId | ID | true | request.body?.["userId"] | | reason | String | true | request.body?.["reason"] | | suspendedByUserId | ID | true | request.body?.["suspendedByUserId"] | | suspendedAt | Date | true | request.body?.["suspendedAt"] | **userId** : Suspended user id **reason** : Reason for suspension action **suspendedByUserId** : Admin ID who performed the suspension action **suspendedAt** : Time of action (suspend/lift) **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/suspensionrecords** ```js axios({ method: 'POST', url: '/v1/suspensionrecords', data: { userId:"ID", reason:"String", suspendedByUserId:"ID", suspendedAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "suspensionRecord", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "suspensionRecord": { "id": "ID", "userId": "ID", "reason": "String", "suspendedByUserId": "ID", "suspendedAt": "Date", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Lift Suspensionrecord` API **[Default update API]** — This is the designated default `update` API for the `suspensionRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin: lift user suspension, set status to lifted & update user isActive=true in auth service. **Rest Route** The `liftSuspensionRecord` API REST controller can be triggered via the following route: `/v1/liftsuspensionrecord/:suspensionRecordId` **Rest Request Parameters** The `liftSuspensionRecord` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | suspensionRecordId | ID | true | request.params?.["suspensionRecordId"] | **suspensionRecordId** : This id paremeter is used to select the required data object that will be updated **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/liftsuspensionrecord/:suspensionRecordId** ```js axios({ method: 'PATCH', url: `/v1/liftsuspensionrecord/${suspensionRecordId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "suspensionRecord", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "suspensionRecord": { "id": "ID", "userId": "ID", "reason": "String", "suspendedByUserId": "ID", "suspendedAt": "Date", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID" } } ``` ### `Get Suspensionrecord` API **[Default get API]** — This is the designated default `get` API for the `suspensionRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a suspension record. Only admin/superAdmin or suspended user. **Rest Route** The `getSuspensionRecord` API REST controller can be triggered via the following route: `/v1/suspensionrecords/:suspensionRecordId` **Rest Request Parameters** The `getSuspensionRecord` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | suspensionRecordId | ID | true | request.params?.["suspensionRecordId"] | **suspensionRecordId** : 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/suspensionrecords/:suspensionRecordId** ```js axios({ method: 'GET', url: `/v1/suspensionrecords/${suspensionRecordId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "suspensionRecord", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "suspensionRecord": { "id": "ID", "userId": "ID", "reason": "String", "suspendedByUserId": "ID", "suspendedAt": "Date", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "user": { "email": "String", "fullname": "String", "roleId": "String" }, "suspendedByUser": { "email": "String", "fullname": "String" } } } ``` ### `List Suspensionrecords` API **[Default list API]** — This is the designated default `list` API for the `suspensionRecord` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List suspension records. Admins see all; users see only their own. **Rest Route** The `listSuspensionRecords` API REST controller can be triggered via the following route: `/v1/suspensionrecords` **Rest Request Parameters** The `listSuspensionRecords` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/suspensionrecords** ```js axios({ method: 'GET', url: '/v1/suspensionrecords', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "suspensionRecords", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "suspensionRecords": [ { "id": "ID", "userId": "ID", "reason": "String", "suspendedByUserId": "ID", "suspendedAt": "Date", "status": "Enum", "status_idx": "Integer", "isActive": true, "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "user": [ { "email": "String", "fullname": "String", "roleId": "String" }, {}, {} ], "suspendedByUser": [ { "email": "String", "fullname": "String" }, {}, {} ] }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Create Auditlog` API **[Default create API]** — This is the designated default `create` API for the `auditLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create audit log entry. Only used by system or admin workflows. **Rest Route** The `createAuditLog` API REST controller can be triggered via the following route: `/v1/auditlogs` **Rest Request Parameters** The `createAuditLog` api has got 6 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | actionType | String | true | request.body?.["actionType"] | | actorUserId | ID | true | request.body?.["actorUserId"] | | targetType | String | true | request.body?.["targetType"] | | targetId | ID | true | request.body?.["targetId"] | | details | Text | false | request.body?.["details"] | | actionAt | Date | true | request.body?.["actionAt"] | **actionType** : Type of admin action (created, updated, suspended, approved, etc.) **actorUserId** : User ID of admin/staff performing the action **targetType** : Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.) **targetId** : ID of the object affected by this action **details** : Freeform details, note, or JSON blob describing action context **actionAt** : When the action occurred **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/auditlogs** ```js axios({ method: 'POST', url: '/v1/auditlogs', data: { actionType:"String", actorUserId:"ID", targetType:"String", targetId:"ID", details:"Text", actionAt:"Date", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "auditLog", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "auditLog": { "id": "ID", "actionType": "String", "actorUserId": "ID", "targetType": "String", "targetId": "ID", "details": "Text", "actionAt": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Get Auditlog` API **[Default get API]** — This is the designated default `get` API for the `auditLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single audit log record. Only superAdmin/admin. **Rest Route** The `getAuditLog` API REST controller can be triggered via the following route: `/v1/auditlogs/:auditLogId` **Rest Request Parameters** The `getAuditLog` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | auditLogId | ID | true | request.params?.["auditLogId"] | **auditLogId** : 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/auditlogs/:auditLogId** ```js axios({ method: 'GET', url: `/v1/auditlogs/${auditLogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "auditLog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "auditLog": { "id": "ID", "actionType": "String", "actorUserId": "ID", "targetType": "String", "targetId": "ID", "details": "Text", "actionAt": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Auditlogs` API **[Default list API]** — This is the designated default `list` API for the `auditLog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. List audit log records. Only superAdmin/admin. **Rest Route** The `listAuditLogs` API REST controller can be triggered via the following route: `/v1/auditlogs` **Rest Request Parameters** The `listAuditLogs` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/auditlogs** ```js axios({ method: 'GET', url: '/v1/auditlogs', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "auditLogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "auditLogs": [ { "id": "ID", "actionType": "String", "actorUserId": "ID", "targetType": "String", "targetId": "ID", "details": "Text", "actionAt": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- # **AUTEURLABB** **FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - AgentHub Service** This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend. This document provides extensive instruction for the usage of agentHub ## Service Access AgentHub service management is handled through service specific base urls. AgentHub service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.). For the agentHub service, the base URLs are: * **Preview:** `https://auteurlabb.prw.mindbricks.com/agenthub-api` * **Staging:** `https://auteurlabb-stage.mindbricks.co/agenthub-api` * **Production:** `https://auteurlabb.mindbricks.co/agenthub-api` ## Scope **AgentHub Service Description** AI Agent Hub AgentHub service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows. **`sys_agentOverride` Data Object**: Runtime overrides for design-time agents. Null fields use the design default. **`sys_agentExecution` Data Object**: Agent execution log. Records each agent invocation with input, output, and performance metrics. **`sys_toolCatalog` Data Object**: Cached tool catalog discovered from project services. Refreshed periodically. ## API Structure ### Object Structure of a Successful Response When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client. **HTTP Status Codes:** * **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully. * **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully. **Success Response Format:** For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below: ```json { "status":"OK", "statusCode": 200, "elapsedMs":126, "ssoTime":120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName":"products", "method":"GET", "action":"list", "appVersion":"Version", "rowCount":3, "products":[{},{},{}], "paging": { "pageNumber":1, "pageRowCount":25, "totalRowCount":3, "pageCount":1 }, "filters": [], "uiPermissions": [] } ``` * **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation. ### Additional Data Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature. ### Error Response If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity: * **400 Bad Request**: The request was improperly formatted or contained invalid parameters. * **401 Unauthorized**: The request lacked a valid authentication token; login is required. * **403 Forbidden**: The current token does not grant access to the requested resource. * **404 Not Found**: The requested resource was not found on the server. * **500 Internal Server Error**: The server encountered an unexpected condition. Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution. ```js { "result": "ERR", "status": 400, "message": "errMsg_organizationIdisNotAValidID", "errCode": 400, "date": "2024-03-19T12:13:54.124Z", "detail": "String" } ``` ## Sys_agentOverride Data Object Runtime overrides for design-time agents. Null fields use the design default. ### Sys_agentOverride Data Object Properties Sys_agentOverride data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `agentName` | String | | Yes | No | Design-time agent name this override applies to. | | `provider` | String | | No | No | Override AI provider (e.g., openai, anthropic). | | `model` | String | | No | No | Override model name. | | `systemPrompt` | Text | | No | No | Override system prompt. | | `temperature` | Double | | No | No | Override temperature (0-2). | | `maxTokens` | Integer | | No | No | Override max tokens. | | `responseFormat` | String | | No | No | Override response format (text/json). | | `selectedTools` | Object | | No | No | Array of tool names from the catalog that this agent can use. | | `guardrails` | Object | | No | No | Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. | | `enabled` | Boolean | | Yes | No | Enable or disable this agent. | | `updatedBy` | ID | | No | No | User who last updated this override. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ## Sys_agentExecution Data Object Agent execution log. Records each agent invocation with input, output, and performance metrics. ### Sys_agentExecution Data Object Properties Sys_agentExecution data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `agentName` | String | | Yes | No | Agent that was executed. | | `agentType` | Enum | | Yes | No | Whether this was a design-time or dynamic agent. | | `source` | Enum | | Yes | No | How the agent was triggered. | | `userId` | ID | | No | No | User who triggered the execution. | | `input` | Object | | No | No | Request input (truncated for large payloads). | | `output` | Object | | No | No | Response output (truncated for large payloads). | | `toolCalls` | Integer | | No | No | Number of tool calls made during execution. | | `tokenUsage` | Object | | No | No | Token usage: { prompt, completion, total }. | | `durationMs` | Integer | | No | No | Execution time in milliseconds. | | `status` | Enum | | Yes | No | Execution status. | | `error` | Text | | No | No | Error message if execution failed. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Enum Properties Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options. - **agentType**: [design, dynamic] - **source**: [rest, sse, kafka, agent] - **status**: [success, error, timeout] ### Filter Properties `agentName` `agentType` `source` `userId` `status` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **agentName**: String has a filter named `agentName` - **agentType**: Enum has a filter named `agentType` - **source**: Enum has a filter named `source` - **userId**: ID has a filter named `userId` - **status**: Enum has a filter named `status` ## Sys_toolCatalog Data Object Cached tool catalog discovered from project services. Refreshed periodically. ### Sys_toolCatalog Data Object Properties Sys_toolCatalog data object has got following properties that are represented as table fields in the database scheme. These properties don't stand just for data storage, but each may have different settings to manage the business logic. | Property | Type | IsArray | Required | Secret | Description | |----------|------|---------|----------|--------|-------------| | `toolName` | String | | Yes | No | Full tool name (e.g., service:apiName). | | `serviceName` | String | | Yes | No | Source service name. | | `description` | Text | | No | No | Tool description. | | `parameters` | Object | | No | No | JSON Schema of tool parameters. | | `lastRefreshed` | Date | | No | No | When this tool was last discovered/refreshed. | * Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set. ### Filter Properties `serviceName` Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API's. - **serviceName**: String has a filter named `serviceName` ## Default CRUD APIs For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation. ### Sys_agentOverride Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | `createAgentOverride` | `/v1/agentoverride` | Yes | | Update | `updateAgentOverride` | `/v1/agentoverride/:sys_agentOverrideId` | Yes | | Delete | `deleteAgentOverride` | `/v1/agentoverride/:sys_agentOverrideId` | Yes | | Get | `getAgentOverride` | `/v1/agentoverride/:sys_agentOverrideId` | Yes | | List | `listAgentOverrides` | `/v1/agentoverrides` | Yes | ### Sys_agentExecution Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getAgentExecution` | `/v1/agentexecution/:sys_agentExecutionId` | Yes | | List | `listAgentExecutions` | `/v1/agentexecutions` | Yes | ### Sys_toolCatalog Default APIs | Operation | API Name | Route | Explicitly Set | |-----------|----------|-------|----------------| | Create | _none_ | - | Auto | | Update | _none_ | - | Auto | | Delete | _none_ | - | Auto | | Get | `getToolCatalogEntry` | `/v1/toolcatalogentry/:sys_toolCatalogId` | Yes | | List | `listToolCatalog` | `/v1/toolcatalog` | Yes | When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property. ## API Reference ### `Get Agentoverride` API **[Default get API]** — This is the designated default `get` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `getAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'GET', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentoverrides` API **[Default list API]** — This is the designated default `list` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentOverrides` API REST controller can be triggered via the following route: `/v1/agentoverrides` **Rest Request Parameters** The `listAgentOverrides` api has got no request parameters. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentoverrides** ```js axios({ method: 'GET', url: '/v1/agentoverrides', data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverrides", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentOverrides": [ { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Update Agentoverride` API **[Default update API]** — This is the designated default `update` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `updateAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `updateAgentOverride` api has got 10 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | | provider | String | | request.body?.["provider"] | | model | String | | request.body?.["model"] | | systemPrompt | Text | | request.body?.["systemPrompt"] | | temperature | Double | | request.body?.["temperature"] | | maxTokens | Integer | | request.body?.["maxTokens"] | | responseFormat | String | | request.body?.["responseFormat"] | | selectedTools | Object | | request.body?.["selectedTools"] | | guardrails | Object | | request.body?.["guardrails"] | | enabled | Boolean | | request.body?.["enabled"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be updated **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **enabled** : Enable or disable this agent. **REST Request** To access the api you can use the **REST** controller with the path **PATCH /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'PATCH', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", enabled:"Boolean", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "PATCH", "action": "update", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Create Agentoverride` API **[Default create API]** — This is the designated default `create` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `createAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride` **Rest Request Parameters** The `createAgentOverride` api has got 9 regular request parameters | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | agentName | String | true | request.body?.["agentName"] | | provider | String | false | request.body?.["provider"] | | model | String | false | request.body?.["model"] | | systemPrompt | Text | false | request.body?.["systemPrompt"] | | temperature | Double | false | request.body?.["temperature"] | | maxTokens | Integer | false | request.body?.["maxTokens"] | | responseFormat | String | false | request.body?.["responseFormat"] | | selectedTools | Object | false | request.body?.["selectedTools"] | | guardrails | Object | false | request.body?.["guardrails"] | **agentName** : Design-time agent name this override applies to. **provider** : Override AI provider (e.g., openai, anthropic). **model** : Override model name. **systemPrompt** : Override system prompt. **temperature** : Override temperature (0-2). **maxTokens** : Override max tokens. **responseFormat** : Override response format (text/json). **selectedTools** : Array of tool names from the catalog that this agent can use. **guardrails** : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }. **REST Request** To access the api you can use the **REST** controller with the path **POST /v1/agentoverride** ```js axios({ method: 'POST', url: '/v1/agentoverride', data: { agentName:"String", provider:"String", model:"String", systemPrompt:"Text", temperature:"Double", maxTokens:"Integer", responseFormat:"String", selectedTools:"Object", guardrails:"Object", }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "201", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "POST", "action": "create", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `Delete Agentoverride` API **[Default delete API]** — This is the designated default `delete` API for the `sys_agentOverride` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `deleteAgentOverride` API REST controller can be triggered via the following route: `/v1/agentoverride/:sys_agentOverrideId` **Rest Request Parameters** The `deleteAgentOverride` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentOverrideId | ID | true | request.params?.["sys_agentOverrideId"] | **sys_agentOverrideId** : This id paremeter is used to select the required data object that will be deleted **REST Request** To access the api you can use the **REST** controller with the path **DELETE /v1/agentoverride/:sys_agentOverrideId** ```js axios({ method: 'DELETE', url: `/v1/agentoverride/${sys_agentOverrideId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentOverride", "method": "DELETE", "action": "delete", "appVersion": "Version", "rowCount": 1, "sys_agentOverride": { "id": "ID", "agentName": "String", "provider": "String", "model": "String", "systemPrompt": "Text", "temperature": "Double", "maxTokens": "Integer", "responseFormat": "String", "selectedTools": "Object", "guardrails": "Object", "enabled": "Boolean", "updatedBy": "ID", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": false } } ``` ### `List Toolcatalog` API **[Default list API]** — This is the designated default `list` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listToolCatalog` API REST controller can be triggered via the following route: `/v1/toolcatalog` **Rest Request Parameters** **Filter Parameters** The `listToolCatalog` api supports 1 optional filter parameter for filtering list results: **serviceName** (`String`): Source service name. - Single (partial match, case-insensitive): `?serviceName=` - Multiple: `?serviceName=&serviceName=` - Null: `?serviceName=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalog** ```js axios({ method: 'GET', url: '/v1/toolcatalog', data: { }, params: { // Filter parameters (see Filter Parameters section above) // serviceName: '' // Filter by serviceName } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalogs", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_toolCatalogs": [ { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Toolcatalogentry` API **[Default get API]** — This is the designated default `get` API for the `sys_toolCatalog` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getToolCatalogEntry` API REST controller can be triggered via the following route: `/v1/toolcatalogentry/:sys_toolCatalogId` **Rest Request Parameters** The `getToolCatalogEntry` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_toolCatalogId | ID | true | request.params?.["sys_toolCatalogId"] | **sys_toolCatalogId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/toolcatalogentry/:sys_toolCatalogId** ```js axios({ method: 'GET', url: `/v1/toolcatalogentry/${sys_toolCatalogId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_toolCatalog", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_toolCatalog": { "id": "ID", "toolName": "String", "serviceName": "String", "description": "Text", "parameters": "Object", "lastRefreshed": "Date", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` ### `List Agentexecutions` API **[Default list API]** — This is the designated default `list` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `listAgentExecutions` API REST controller can be triggered via the following route: `/v1/agentexecutions` **Rest Request Parameters** **Filter Parameters** The `listAgentExecutions` api supports 5 optional filter parameters for filtering list results: **agentName** (`String`): Agent that was executed. - Single (partial match, case-insensitive): `?agentName=` - Multiple: `?agentName=&agentName=` - Null: `?agentName=null` **agentType** (`Enum`): Whether this was a design-time or dynamic agent. - Single: `?agentType=` (case-insensitive) - Multiple: `?agentType=&agentType=` - Null: `?agentType=null` **source** (`Enum`): How the agent was triggered. - Single: `?source=` (case-insensitive) - Multiple: `?source=&source=` - Null: `?source=null` **userId** (`ID`): User who triggered the execution. - Single: `?userId=` - Multiple: `?userId=&userId=` - Null: `?userId=null` **status** (`Enum`): Execution status. - Single: `?status=` (case-insensitive) - Multiple: `?status=&status=` - Null: `?status=null` **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecutions** ```js axios({ method: 'GET', url: '/v1/agentexecutions', data: { }, params: { // Filter parameters (see Filter Parameters section above) // agentName: '' // Filter by agentName // agentType: '' // Filter by agentType // source: '' // Filter by source // userId: '' // Filter by userId // status: '' // Filter by status } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecutions", "method": "GET", "action": "list", "appVersion": "Version", "rowCount": "\"Number\"", "sys_agentExecutions": [ { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true }, {}, {} ], "paging": { "pageNumber": "Number", "pageRowCount": "NUmber", "totalRowCount": "Number", "pageCount": "Number" }, "filters": [], "uiPermissions": [] } ``` ### `Get Agentexecution` API **[Default get API]** — This is the designated default `get` API for the `sys_agentExecution` data object. Frontend generators and AI agents should use this API for standard CRUD operations. **Rest Route** The `getAgentExecution` API REST controller can be triggered via the following route: `/v1/agentexecution/:sys_agentExecutionId` **Rest Request Parameters** The `getAgentExecution` api has got 1 regular request parameter | Parameter | Type | Required | Population | | ---------------------- | ---------------------- | -------- | ---------------------------- | | sys_agentExecutionId | ID | true | request.params?.["sys_agentExecutionId"] | **sys_agentExecutionId** : This id paremeter is used to query the required data object. **REST Request** To access the api you can use the **REST** controller with the path **GET /v1/agentexecution/:sys_agentExecutionId** ```js axios({ method: 'GET', url: `/v1/agentexecution/${sys_agentExecutionId}`, data: { }, params: { } }); ``` **REST Response** ```json { "status": "OK", "statusCode": "200", "elapsedMs": 126, "ssoTime": 120, "source": "db", "cacheKey": "hexCode", "userId": "ID", "sessionId": "ID", "requestId": "ID", "dataName": "sys_agentExecution", "method": "GET", "action": "get", "appVersion": "Version", "rowCount": 1, "sys_agentExecution": { "id": "ID", "agentName": "String", "agentType": "Enum", "agentType_idx": "Integer", "source": "Enum", "source_idx": "Integer", "userId": "ID", "input": "Object", "output": "Object", "toolCalls": "Integer", "tokenUsage": "Object", "durationMs": "Integer", "status": "Enum", "status_idx": "Integer", "error": "Text", "recordVersion": "Integer", "createdAt": "Date", "updatedAt": "Date", "_owner": "ID", "isActive": true } } ``` **After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.** --- --- ## Related Documentation For more detailed information, refer to: - **[llms.txt](/document/llms.txt)** - Documentation overview and index - **[llms-restapi.txt](/document/llms-restapi.txt)** - Complete REST API reference - **[llms-full.txt](/document/llms-full.txt)** - Complete documentation --- *Generated by Mindbricks Genesis Engine*