Workforce Operating System - Frontend Development Prompts
AI-assisted frontend development prompts for Workforce Operating System
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
- Project Introduction & Setup
- Authentication Management
- Verification Management
- Profile Management
- User Management
- MCP BFF Integration
- EmployeeProfile Service
- ScheduleManagement Service
- AttendanceManagement Service
- TaskManagement Service
- LeaveManagement Service
- PayrollReporting Service
- AnnouncementManagement Service
- AiWorkforceAnalytics Service
- SubscriptionManagement Service
- SubscriptionManagement Service CompanySubscription Payment Flow
- AgentHub Service
Introduction
Project Overview
Workforce Operating System
Version : 1.0.355
WorkforceOS is a unified, web-based platform that enables businesses to efficiently manage employees, schedules, attendance, tasks, and workforce operations with full company-level data isolation. Designed for multi-role access, internal departments, AI-driven insights, and integrated communication via email and in-app notifications.
How to Use Project Documents
The Workforceos 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://workforceos.prw.mindbricks.com/auth-api |
| Staging | https://workforceos-stage.mindbricks.co/auth-api |
| Production | https://workforceos.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 Workforceos 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 -
Event Guide – helpful for event-driven or cross-service integrations
Auth Event Guide -
Service Design Document – overall structure, patterns, and logic
Auth Service Design
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 -
Event Guide – syncing strategies across replicas
BFF Event Guide -
Service Design – aggregation patterns and index structures
BFF Service Design
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 Workforce Operating System 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.
Available Business Services
employeeProfile Service
Description: Manages extended employee profile data, employment/tax details, and employee-related documents/certifications for each company. Extends user identities with HR, department, and compliance info. Allows managers and admins to review employee profiles and documents…
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/employeeprofile-api |
| Staging | https://workforceos-stage.mindbricks.co/employeeprofile-api |
| Production | https://workforceos.mindbricks.co/employeeprofile-api |
scheduleManagement Service
Description: Microservice managing shift scheduling, shift templates, assignment of users/departments to shifts, and schedule conflict detection for WorkforceOS.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/schedulemanagement-api |
| Staging | https://workforceos-stage.mindbricks.co/schedulemanagement-api |
| Production | https://workforceos.mindbricks.co/schedulemanagement-api |
attendanceManagement Service
Description: Handles employee attendance logging (check-in/out), attendance rules (lateness/absence/early-leave), real-time & historical logs, and publishes notification events. Enforces company data isolation, strict record uniqueness, and one-per-shift attendance rule.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/attendancemanagement-api |
| Staging | https://workforceos-stage.mindbricks.co/attendancemanagement-api |
| Production | https://workforceos.mindbricks.co/attendancemanagement-api |
taskManagement Service
Description: Handles creation, assignment, update, and tracking of tasks tied to employees, shifts, or departments. Supports admins/managers assigning tasks; employees viewing and completing tasks; accountability tracking. Exposes APIs for creating, updating, deleting, and listing tasks with data enrichment. Data is .company-tenant-scoped…
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/taskmanagement-api |
| Staging | https://workforceos-stage.mindbricks.co/taskmanagement-api |
| Production | https://workforceos.mindbricks.co/taskmanagement-api |
leaveManagement Service
Description: Handles employee leave/absence requests, review/approval workflows, and automatic integration with shift assignments, ensuring company data isolation and leave history access for employees and managers/admins.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/leavemanagement-api |
| Staging | https://workforceos-stage.mindbricks.co/leavemanagement-api |
| Production | https://workforceos.mindbricks.co/leavemanagement-api |
payrollReporting Service
Description: Handles payroll report records for employees based on calculated hours, overtime, absences from attendance/leave. Provides summary views by user/period/department, allows payment status entry (not processing). Employees can view their own reports. Company tenant scoped and RBAC-enforced.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/payrollreporting-api |
| Staging | https://workforceos-stage.mindbricks.co/payrollreporting-api |
| Production | https://workforceos.mindbricks.co/payrollreporting-api |
announcementManagement Service
Description: Handles company-wide and department-specific announcements, supporting scheduled or immediate delivery. Enables admins/managers to create, edit, and manage rich-text announcements, assign audience (all/company/department/users), and triggers events for notification delivery. Employees see relevant announcements in history/detail. Fully tenant-scoped.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/announcementmanagement-api |
| Staging | https://workforceos-stage.mindbricks.co/announcementmanagement-api |
| Production | https://workforceos.mindbricks.co/announcementmanagement-api |
aiWorkforceAnalytics Service
Description: Microservice for computing and delivering AI-powered workforce analytics (e.g., shift optimization, absenteeism insights, staffing trends) for eligible (subscribed) companies. Handles insight calculation, storage, and secure distribution to authorized users. Publishes insight alerts/events for notifications. Strictly enforces company data isolation and subscription gating on all features.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/aiworkforceanalytics-api |
| Staging | https://workforceos-stage.mindbricks.co/aiworkforceanalytics-api |
| Production | https://workforceos.mindbricks.co/aiworkforceanalytics-api |
subscriptionManagement Service
Description: Manages company AI subscriptions through Stripe payments. Companies must pay via Stripe to activate AI features—no manual subscription creation allowed. Handles the full Stripe payment lifecycle: checkout, payment confirmation, activation, and cancellation. The subscription status is entirely driven by Stripe webhook events. SuperAdmin/saasAdmin bypass payment for platform management.
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/subscriptionmanagement-api |
| Staging | https://workforceos-stage.mindbricks.co/subscriptionmanagement-api |
| Production | https://workforceos.mindbricks.co/subscriptionmanagement-api |
agentHub Service
Description: AI Agent Hub
Documentation:
Base URL Examples:
| Environment | URL |
|---|---|
| Preview | https://workforceos.prw.mindbricks.com/agenthub-api |
| Staging | https://workforceos-stage.mindbricks.co/agenthub-api |
| Production | https://workforceos.mindbricks.co/agenthub-api |
Connect via MCP (Model Context Protocol)
All backend services in the Workforceos 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://workforceos.prw.mindbricks.com/mcpbff-api/mcp |
https://workforceos.prw.mindbricks.com/mcpbff-api/mcp/sse |
| Staging | https://workforceos-stage.mindbricks.co/mcpbff-api/mcp |
https://workforceos-stage.mindbricks.co/mcpbff-api/mcp/sse |
| Production | https://workforceos.mindbricks.co/mcpbff-api/mcp |
https://workforceos.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_hereAPI 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:
{
"mcpServers": {
"workforceos": {
"url": "https://workforceos.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):
{
"mcpServers": {
"workforceos": {
"url": "https://workforceos.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 Workforce Operating System 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:
- Feature Description - What the feature does and its purpose
- Data Models - The backend data structures to work with
- API Endpoints - Available REST APIs for the feature
- UI Requirements - Specific user interface requirements
- 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
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Project Introduction & Setup
This is the introductory document for the workforceos 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
WorkforceOS is a unified, web-based platform that enables businesses to efficiently manage employees, schedules, attendance, tasks, and workforce operations with full company-level data isolation. Designed for multi-role access, internal departments, AI-driven insights, and integrated communication via email and in-app notifications.
Project Services Overview
The project has 1 auth service, 1 notification service, 1 BFF service, and 10 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 | employeeProfile | Manages extended employee profile data, employment/tax details, and employee-rel… | /employeeProfile-api |
| 3 | scheduleManagement | Microservice managing shift scheduling, shift templates, assignment of users/dep… | /scheduleManagement-api |
| 4 | attendanceManagement | Handles employee attendance logging (check-in/out), attendance rules (lateness/a… | /attendanceManagement-api |
| 5 | taskManagement | Handles creation, assignment, update, and tracking of tasks tied to employees, s… | /taskManagement-api |
| 6 | leaveManagement | Handles employee leave/absence requests, review/approval workflows, and automati… | /leaveManagement-api |
| 7 | payrollReporting | Handles payroll report records for employees based on calculated hours, overtime… | /payrollReporting-api |
| 8 | announcementManagement | Handles company-wide and department-specific announcements, supporting scheduled… | /announcementManagement-api |
| 9 | aiWorkforceAnalytics | Microservice for computing and delivering AI-powered workforce analytics (e.g., … | /aiWorkforceAnalytics-api |
| 10 | subscriptionManagement | Manages company AI subscriptions through Stripe payments. Companies must pay via… | /subscriptionManagement-api |
| 11 | 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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
Accessing the Backend Using Rest API
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://workforceos.prw.mindbricks.com - Staging:
https://workforceos-stage.mindbricks.co - Production:
https://workforceos.mindbricks.co
For the auth service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/auth-api - Staging:
https://workforceos-stage.mindbricks.co/auth-api - Production:
https://workforceos.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.
Multi-Tenancy Management
THIS APPLICATION IS MULTI-TENANT
This application is multi-tenant. Tenant data is isolated per company, and tenant-level records are attached to companyId.
For frontend, tenant context is resolved from frontend routing context (URL prefix in preview/test, subdomain in production) and then forwarded to backend through header.
Tenant Routing Contract (Required)
- SaaS pages:
/ - Tenant pages:
/{tenantCodename}/... - Example:
/babil/login - All tenant-specific pages must keep
/{tenantCodename}prefix.
In preview/test, URL prefix simulates tenant selection. In production, tenant is usually resolved from subdomain (e.g. babil.appname...).
In both modes, backend tenant targeting must always be done by header.
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL/subdomain is only a frontend tenant selection mechanism. Backend API calls must always claim tenant with header.
If no tenant codename is sent, backend assumes SaaS/root tenant (root).
Sample Company Tenant
The application backend also includes a sample tenant created with a sample tenant owner, who has the same email and password of the superadmin. This sample is created in the backend to be able to test the multi-tenant behaviour of the frontend at the beginning.
The sample company has codename babil. Use /babil/... prefixed pages and send mbx-company-codename: babil in tenant-scoped requests for testing.
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.
Since this is a multi-tenant application, SaaS home and tenant home should be different.
SaaS Home (/)
Build a landing page with:
- Left area: project full name and project description
- Two primary buttons:
- Login To SaaS (root tenant login entry)
- Register New Company (show only when tenant owner registration is public)
- Bottom small link: See Companies
When user clicks See Companies, open a left sliding drawer and fetch tenant list with listBriefCompanies.
Clicking a tenant should navigate to /{tenantCodename} tenant homepage.
Tenant Home (/{tenantCodename})
Create a simple tenant homepage that shows tenant name/fullname/avatar and includes:
- Login button
- Register button only when tenant-user registration is public
Tenant homepage data should be fetched with tenant-level public API getCompanyHome while sending mbx-company-codename from URL context.
All tenant pages should keep tenant context in frontend routing. Regardless of routing method, all backend calls from tenant context must include mbx-company-codename header.
Tenant API Contract (Current)
Use the following auth APIs for tenant information access:
- Public brief list for landing/tenant selection:
listBriefCompanies - Public brief single tenant:
getBriefCompany(/briefcompanies/:codename) - Public tenant-home read in tenant scope:
getCompanyHome(/companyhome/:codename) - Logged-in tenant-level read:
getCompany(/companies, tenant id resolved from tenant context/session) - Tenant profile read for tenant managers:
getCompanyProfile(/companyprofile, id resolved from tenant header/session) - SaaS-level tenant account read/list:
getCompanyAccountandlistCompaniesAccounts
List Briefcompanies API
Get a list of companies, this route can be called by public, no login required
Rest Route
The listBriefCompanies API REST controller can be triggered via the following route:
/v1/briefcompanies
Rest Request Parameters
The listBriefCompanies api has got no request parameters.
REST Request To access the api you can use the REST controller with the path GET /v1/briefcompanies
axios({
method: 'GET',
url: '/v1/briefcompanies',
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companies",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"companies": [
{
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Get Companyhome API
Get public tenant-home information in tenant level.
Rest Route
The getCompanyHome API REST controller can be triggered via the following route:
/v1/companyhome/:codename
Rest Request Parameters
The getCompanyHome api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| codename | String | true | request.params?.[“codename”] |
| codename : The codename of the company to fetch |
REST Request To access the api you can use the REST controller with the path GET /v1/companyhome/:codename
axios({
method: 'GET',
url: `/v1/companyhome/${codename}`,
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"company": {
"isActive": true
}
}
Get Company API
Get a company in current tenant scope. A protected tenant-level route for logged-in users.
Rest Route
The getCompany API REST controller can be triggered via the following route:
/v1/companies
Rest Request Parameters
The getCompany api has got no request parameters.
REST Request To access the api you can use the REST controller with the path GET /v1/companies
axios({
method: 'GET',
url: '/v1/companies',
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companyprofile API
Get tenant profile information in tenant level. A private route for tenantOwner and tenantAdmin.
Rest Route
The getCompanyProfile API REST controller can be triggered via the following route:
/v1/companyprofile
Rest Request Parameters
The getCompanyProfile api has got no request parameters.
REST Request To access the api you can use the REST controller with the path GET /v1/companyprofile
axios({
method: 'GET',
url: '/v1/companyprofile',
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companyaccount API
Get tenant account information by id. A private SaaS-level route for superAdmin, saasAdmin and saasUser.
Rest Route
The getCompanyAccount API REST controller can be triggered via the following route:
/v1/companyaccounts/:companyId
Rest Request Parameters
The getCompanyAccount api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| companyId | ID | true | request.params?.[“companyId”] |
| companyId : The id of the company account to fetch |
REST Request To access the api you can use the REST controller with the path GET /v1/companyaccounts/:companyId
axios({
method: 'GET',
url: `/v1/companyaccounts/${companyId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Companiesaccounts API
List tenant accounts in SaaS level for superAdmin, saasAdmin and saasUser.
Rest Route
The listCompaniesAccounts API REST controller can be triggered via the following route:
/v1/companyaccounts
Rest Request Parameters
Filter Parameters
The listCompaniesAccounts api supports 5 optional filter parameters for filtering list results:
name (String): A string value to represent one word name of the company
- Single (partial match, case-insensitive):
?name=<value> - Multiple:
?name=<value1>&name=<value2> - Null:
?name=null
codename (String): A string value to represent a unique code name for the company which is generated automatically using name
- Single (partial match, case-insensitive):
?codename=<value> - Multiple:
?codename=<value1>&codename=<value2> - Null:
?codename=null
fullname (String): A string value to represent the fullname of the company
- Single (partial match, case-insensitive):
?fullname=<value> - Multiple:
?fullname=<value1>&fullname=<value2> - Null:
?fullname=null
avatar (String): A string value represent the url of the company avatar. Keep null for random avatar.
- Single (partial match, case-insensitive):
?avatar=<value> - Multiple:
?avatar=<value1>&avatar=<value2> - Null:
?avatar=null
ownerId (ID): An ID value to represent the user id of company owner who created the tenant
- Single:
?ownerId=<value> - Multiple:
?ownerId=<value1>&ownerId=<value2> - Null:
?ownerId=null
REST Request To access the api you can use the REST controller with the path GET /v1/companyaccounts
axios({
method: 'GET',
url: '/v1/companyaccounts',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// name: '<value>' // Filter by name
// codename: '<value>' // Filter by codename
// fullname: '<value>' // Filter by fullname
// avatar: '<value>' // Filter by avatar
// ownerId: '<value>' // Filter by ownerId
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companies",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"companies": [
{
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Do not use deprecated tenant APIs such as getCompanyByCodename or listRegisteredCompanies.
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:
SaaS Level:
- Home / Landing
- Login (SaaS)
- Dashboard (after login)
Tenant Level (/{tenantCodename}/...):
- Tenant Home
- Login
- Register
- Verification
- Profile
- User Management (admin)
- EmployeeProfile Service Pages
- ScheduleManagement Service Pages
- AttendanceManagement Service Pages
- TaskManagement Service Pages
- LeaveManagement Service Pages
- PayrollReporting Service Pages
- AnnouncementManagement Service Pages
- AiWorkforceAnalytics Service Pages
- SubscriptionManagement 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:
- Project infrastructure — routing (using
react-routerv7 — import fromreact-router, notreact-router-dom), layout, environment config, API client setup (one client per service) - Home page with environment selector, login/register buttons, project description
- SaaS landing and Tenant home pages with tenant selection drawer
- Placeholder pages for all navigation items listed above
- 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
- When the application starts, please ensure that the
baseUrlis set to the production server URL, and that the environment selector dropdown has the Production option selected by default. - Note that any API call to the application backend is based on a service base URL. Auth APIs use
/auth-apiprefix, and each business service uses/{serviceName}-apiprefix after the application’s base URL. - 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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Authentication Management
This document covers the authentication features of the workforceos project: registration, login, logout, and session management. The project introduction, API conventions, 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://workforceos.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 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
Defaults if not configured:
| Environment | Default |
|---|---|
| dev | http://localhost:5173 |
| test | https://workforceos.prw.mindbricks.com |
| stage | https://workforceos-stage.mindbricks.co |
| prod | https://workforceos.mindbricks.co |
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
Since the application is multi-tenant, there will be two registration process. First one is the company register and the other one is user registration.
Users are either in SaaS level, like administrators, or in company tenant level like company owners, admins and users.
SaaS Level User Registration
SaaS user registration is not public in the application, SaaS users can only be created through createUser api which can be called by the superAdmin or saasAdmin of the SaaS level. Creating a new SaaS user is handled through admin panel which will be described in the next prompt.
SaaS users belong to root tenant context and should login from the SaaS entry page. Tenant-end users should not use this login entry.
Tenant -company- Registration
Tenant registraration, creating a new company, is always handled together with tenant owner registration.
Both tenant and tenant owner registration are public in the application, so there will be a company registration page in the frontend, that any user can provide their user and company information together.
Using the registercompanyOwner route of the auth API, send the required fields from your registration page. Please create a simple and polished registration page that includes only the necessary fields of the registration API.
The registerCompanyOwner API in the auth service is described with the request and response structure below.
Note that since the registerCompanyOwner API is a business API, it is versioned; call it with the given version like /v1/registercompanyOwner.
Registering a company and its owner is indeed a user registration which also creates a company and assigns its ownership to the created user. The created user instance will have got the id of the company in its `companyId property automatically.
The provided api body should also include a nested object for the company data object instance to be created.
{
//..
"email": "joe.doe@example.com",
"fullname": "Joe Doe",
"avatar": "...",
//..
"company": {
//..
"name": "Babil",
"fullname": "Babil Online BookStore Ltd.",
"avatar": "..."
}
}
Register Companyowner API
This api is used by public users to register themselves as tenant owners to create both a user account and a company account they own.
Rest Route
The registerCompanyOwner API REST controller can be triggered via the following route:
/v1/registercompanyowner
Rest Request Parameters
The registerCompanyOwner api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| avatar | String | false | request.body?.[“avatar”] |
| socialCode | String | false | request.body?.[“socialCode”] |
| password | String | true | request.body?.[“password”] |
| String | true | request.body?.[“email”] | |
| company | Object | true | request.body?.[“company”] |
| fullname | String | true | request.body?.[“fullname”] |
| avatar : The avatar url of the user. If not sent, a default random one will be generated. | |||
| socialCode : Send this social code if it is sent to you after a social login authetication of an unregistred user. The users profile data will be complemented from the autheticated social profile using this code. If you provide the social code there is no need to give full profile data of the user, just give the ones that are not included in social profiles. | |||
| password : The password defined by the the user that is being registered. | |||
| email : The email defined by the the user that is being registered. | |||
| company : The company informatiion for the tenant that the created user will own. | |||
| fullname : The full name 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/registercompanyowner
axios({
method: 'POST',
url: '/v1/registercompanyowner',
data: {
avatar:"String",
socialCode:"String",
password:"String",
email:"String",
company:"Object",
fullname:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
"company": "Object"
}
After a successful registration, the frontend code should handle verification requirements with the same flow style as single-tenant mode. The registration response will include a user object in the root envelope; this object contains user information with an id field.
Tenant -company- User Registration
User registration for company tenants is public in the application. Please create a simple and polished registration page that includes only the necessary fields of the registration API.
This registration targets an existing company, so the tenant context must be provided — attach the company codename to the request header.
Using the registercompanyuser route of the auth API, send the required fields from your registration page.
The registerCompanyUser API in the auth service is described with the request and response structure below.
Note that since the registerCompanyUser API is a business API, it is versioned; call it with the given version like /v1/registercompanyuser.
Register Companyuser API
This route is used by public users to register themselves to tenants that are created by tenant owners.
Rest Route
The registerCompanyUser API REST controller can be triggered via the following route:
/v1/registercompanyuser
Rest Request Parameters
The registerCompanyUser api has got 5 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| socialCode | String | false | request.body?.[“socialCode”] |
| password | String | true | request.body?.[“password”] |
| String | true | request.body?.[“email”] | |
| fullname | String | true | request.body?.[“fullname”] |
| avatar | String | false | request.body?.[“avatar”] |
| socialCode : Send this social code if it is sent to you after a social login authetication of an unregistred user. The users profile data will be complemented from the autheticated social profile using this code. If you provide the social code there is no need to give full profile data of the user, just give the ones that are not included in social profiles. | |||
| password : The password defined by the the user that is being registered. | |||
| email : The email defined by the the user that is being registered. | |||
| fullname : The full name defined by the the user that is being registered. | |||
| avatar : The avatar url of the user. A random avatar will be generated if not provided |
REST Request To access the api you can use the REST controller with the path POST /v1/registercompanyuser
axios({
method: 'POST',
url: '/v1/registercompanyuser',
data: {
socialCode:"String",
password:"String",
email:"String",
fullname:"String",
avatar:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
After a successful registration, the frontend code should handle verification requirements with the same flow style as single-tenant mode. 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.
Note that the session/currentuser response has 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
usernameoremailfields (if both exist,usernameis prioritized). Themobilefield is also accepted when the user has a mobile number on file.
Example
axios.post("/login", {
email: "user@example.com",
password: "securePassword"
});
Success Response
{
"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
userBucketTokenis 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 regularaccessToken. 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. TheaccessTokenis valid but all protected API calls will return403until 2FA is completed. Do not treat this login as successful — instead, store theaccessToken,userId, andsessionId, 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 credentials403 Forbidden: Email/mobile verification or 2FA pending400 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
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
{ "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
axios.get("/currentuser", {
headers: { Authorization: "Bearer <jwt>" }
});
Success (200)
Returns the session object (identity, tenancy, token metadata):
{
"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
{ "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:
- The raw
/currentuserAPI mixes session and user data into a single flat envelope. There is noidproperty on the raw response — useuserIdandsessionId. - Note that any API call to the auth service should use the
/auth-apiprefix 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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Verification Management
This document is a part of a REST API guide for the workforceos 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 10 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://workforceos.prw.mindbricks.com/auth-api - Staging:
https://workforceos-stage.mindbricks.co/auth-api - Production:
https://workforceos.mindbricks.co/auth-api
Any request that requires login must include a valid token in the Bearer authorization header.
Multi-Tenancy Management
THIS APPLICATION IS MULTI-TENANT
This application is mult-tanant, it means; as a SaaS application, it isolates each tenant-data from each other. The tenants are called company and a data object with the same name exist to store and manage the tenant information. The company data instances are referenced from other data objects or entities as companyId. Any data object which is in tenant level (some data objects may still stay in SaaS level) has a companyId property which attaches it to a company tenant. But this value is added to the data object instance in the time of creation by the system according to the current company user is navigating.
For the human readability each company has also got a companyCodename which is a unique form of its name. Any api call to the application should claim its target company tenant, so it should provide companyCodename parameter at one of the following request locations.
// In header with special header name
headers["mbx-company-codename"] = "babil",
// or in query with ( _company ) parameter
const url = `${serviceUrl}/v1/users/${userId}?_company=babil`
// or in post body with ( _company ) parameter
const body = {
//...
_company: "babil",
//...
}
When no companyCodename is given in the related parameters, application will assume that the access targets the root target, the Saas level. The companyCodename of SaaS level is always root. When no companyCodename is specified, root is assumed as the current companyCodename.
Note that, logins and registrations are all tenant scoped. If any a tenant-lvel api is login-required then it will check for a company specific token according to the target company defined in a related parameter with its codename. The application creates the cookies with companyCodename prefixes but it is recommended for the frontend application to populate the bearer header with the user’s company related token.
Not that all company tenants are managed in the same backend services, however a company tanant frontend should be specific to one company. Frontend should have a technical way to understand which company is targeted by the user, for production frontend application this should be managed by the subdomains that represents the codename of the company like,
https://babil.storeCreator.com
Using the subdomain, frontend will distinguish that the codename is babil and will atatch it to all tenant-level api calls.
The url may also be used for the SaaS directly with a more general wording like,
https://www.storeCreator.com
However, this subdomain management may not be handled easily in the AI frontend builders that they use their own preview urls, an other url structure should be handled to simulate the subdomain behaviour for tenant forwarding.
It may be like,
https://{somePreviewUrlOfABuilderPlatform}/babil/login
In some way, frontend should provide a simple and practical way to the user to target a specific tenant.
Sample Company Tenant
The applcation backend also includes a sample tenant created with a sample tenant owner, who has the same login identifier and password as the superadmin. This sample is created in the backend to be able to test the multi-tenant behaviour of the frontend at the beginning.
The sample company has a codename babil and can be targetd by attaching this codename to the API calls. So whwn the front end home page is built, homepages both for the SaaS and tenant shoul be created and ready to be tested.
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.
{
//...
"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.
- Call the email verification
startroute 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 thesecretCodeproperty of the response. - 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
secretCodeis sent to the frontend for testing, display it on the input page so the user can copy and paste it. - The
startresponse includes acodeIndexproperty. Display its value on the input page so the user can match the index in the message with the one on the screen. - When the user submits the code, complete the email verification using the
completeroute of the backend (described below) with the user’s email and the secret code. - 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
{ "email": "user@example.com" }
Success Response
{
"status": "OK",
"codeIndex": 1,
"timeStamp": 1784578660000,
"date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
"expireTime": 86400,
"verificationType": "byLink",
"secretCode": "123456",
"userId": "user-uuid"
}
⚠️ In production,
secretCodeis not returned — it is only sent via email.
Error Responses
400 Bad Request: Already verified403 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
{
"status": "OK",
"isVerified": true,
"email": "user@email.com",
"userId": "user-uuid"
}
Error Responses
403 Forbidden: Code expired or mismatched404 Not Found: No verification in progress
Resetting Password
Users can reset their forgotten passwords without a login required, through email verification. To be able to start a password reset flow, users will click on the “Reset Password” link in the login page.
Password Reset By Email Flow
- Call the password reset by email verification
startroute 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 thesecretCodeproperty of the response. - 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
secretCodeis sent to the frontend for testing, display it on the input page so the user can copy and paste it. - The
startresponse includes acodeIndexproperty. Display its value on the input page so the user can match the index in the message with the one on the screen. - The input page should also include a double input area for the user to enter and confirm their new password.
- When the user submits the code and the new password, complete the password reset by email using the
completeroute of the backend (described below) with the user’s email, the secret code and new password. - 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 |
|---|---|---|---|
| String | Yes | The email address of the user |
{
"email": "user@example.com"
}
Success Response
Returns secret code details (only in development environment) and confirmation that the verification step has been started.
{
"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 |
|---|---|---|---|
| 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 |
{
"email": "user@example.com",
"secretCode": "123456",
"password": "newSecurePassword123"
}
Success Response
{
"userId": "user-uuid",
"email": "user@example.com",
"isVerified": true
}
Error Responses
403 Forbidden:- Secret code mismatch
- Secret code expired
- No ongoing verification found
Two-Factor Authentication (2FA)
This project has email 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
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
- After a successful login, check the response for
sessionNeedsEmail2FAorsessionNeedsMobile2FA(login returns 200 with the full session —accessToken,userId,sessionIdand all user fields — plus the 2FA flag). - If either flag is
true, do not treat the user as authenticated and do not navigate to the app home. The token fromuseLoginis already stored automatically; it’s a partial token though — the backend’senforce2FA(session)will reject every protected call withEmailTwoFactorNeeded/MobileTwoFactorNeeded403 until the 2FA flag is cleared. Only the 2FA verification endpoints (and/currentuser) accept it as-is. - Navigate the user to a 2FA verification page instead of
/. - On the 2FA page, immediately call the 2FA
startendpoint (described below). The user / session are read from the auth header — nouserIdorsessionIdin the payload. This triggers sending the verification code to the user’s email. - 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. - The
startresponse includes acodeIndexproperty. Display its value on the page so the user can match the index in the message with the one on the screen. - When the user submits the code, call the 2FA
completeendpoint with justsecretCodein the body (the auth header carries the user / session identity). - On success, the
completeendpoint returns the updated session object with the 2FA flag cleared. Now set the user as fully authenticated and navigate to the main application page. - Provide a “Resend Code” button with a 60-second cooldown to prevent spam.
- Provide a “Cancel” option that discards the partial session and returns the user to the login page.
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
{
"userId": "user-uuid",
"sessionId": "session-uuid"
}
Success Response
{
"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,
secretCodeis 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:
{
"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 expired403 Forbidden: No ongoing verification found401 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
accessTokenfrom login remains the same throughout the 2FA flow — you do not get a new token. Thecompleteresponse returns the same session with the 2FA flag cleared. /currentuserworks during 2FA: The/currentuserendpoint does not enforce 2FA, so it can be called during the 2FA flow. However, all other protected endpoints will return403.
Navigating the Login Page
Please note that since this application is multitenant, the login page that will be navigated to after a verification process, should be aware of the tenant company.
If this login navigate is after a user registration (or after a post-registration verification) to a company, then keep the active company as the original and navigate user to the selected company.
If this login navigate is after a company registration (or after a tenant post-registration verification),
then you have a new company other than the root one, so you should make this new tenant as the selected one and navigate to its login page.
If this login is after a post-login verification, then keep the original company that the previous login attempt is made to and navigate to the same company either it is the root or andy registered company.
** 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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - Profile Management
This document is a part of a REST API guide for the workforceos 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 10 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://workforceos.prw.mindbricks.com - Staging:
https://workforceos-stage.mindbricks.co - Production:
https://workforceos.mindbricks.co
For the auth service, service urls are as follows:
- Preview:
https://workforceos.prw.mindbricks.com/auth-api - Staging:
https://workforceos-stage.mindbricks.co/auth-api - Production:
https://workforceos.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.
Multi-Tenancy Management
THIS APPLICATION IS MULTI-TENANT
This application is mult-tanant, it means; as a SaaS application, it isolates each tenant-data from each other. The tenants are called company and a data object with the same name exist to store and manage the tenant information. The company data instances are referenced from other data objects or entities as companyId. Any data object which is in tenant level (some data objects may still stay in SaaS level) has a companyId property which attaches it to a company tenant. But this value is added to the data object instance in the time of creation by the system according to the current company user is navigating.
For human readability each company has also got a companyCodename which is a unique form of its name.
Frontend must forward tenant targeting with the tenant header:
headers["mbx-company-codename"] = "babil";
When no companyCodename is given in the related parameters, application will assume that the access targets the root target, the Saas level. The companyCodename of SaaS level is always root. When no companyCodename is specified, root is assumed as the current companyCodename.
Note that, logins and registrations are all tenant scoped. If any a tenant-lvel api is login-required then it will check for a company specific token according to the target company defined in a related parameter with its codename. The application creates the cookies with companyCodename prefixes but it is recommended for the frontend application to populate the bearer header with the user’s company related token.
Not that all company tenants are managed in the same backend services, however a company tanant frontend should be specific to one company. Frontend should have a technical way to understand which company is targeted by the user, for production frontend application this should be managed by the subdomains that represents the codename of the company like,
https://babil.storeCreator.com
Using the subdomain, frontend will distinguish that the codename is babil and will atatch it to all tenant-level api calls.
The url may also be used for the SaaS directly with a more general wording like,
https://www.storeCreator.com
However, this subdomain management may not be handled easily in the AI frontend builders that they use their own preview urls, an other url structure should be handled to simulate the subdomain behaviour for tenant forwarding.
It may be like,
https://{somePreviewUrlOfABuilderPlatform}/babil/login
In some way, frontend should provide a simple and practical way to the user to target a specific tenant.
Sample Company Tenant
The applcation backend also includes a sample tenant created with a sample tenant owner, who has the same email and password of the superadmin. This sample is created in the backend to be able to test the multi-tenant behaviour of the frontend at the beginning.
The sample company has a codename babil and can be targetd by attaching this codename to the API calls. So whwn the front end home page is built, homepages both for the SaaS and tenant shoul be created and ready to be tested.
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):
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:
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 <img> tags without any authentication token:
<img src={user.avatar} alt="Avatar" />
Company Avatar Bucket
Upload: POST {authBaseUrl}/bucket/companyAvatars/upload
Download by ID: GET {authBaseUrl}/bucket/companyAvatars/download/{fileId}
Download by Key: GET {authBaseUrl}/bucket/companyAvatars/download/key/{accessKey}
Same configuration as user avatars: public read, authenticated write, images only, 5 MB max.
Upload and display work the same way — upload the image, store the download URL in the company’s avatar field.
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 |
| getCompanyAvatarsFile | GET | /v1/companyAvatarsFiles/:id | Get tenant avatar metadata |
| listCompanyAvatarsFiles | GET | /v1/companyAvatarsFiles | List tenant avatars |
| deleteCompanyAvatarsFile | DELETE | /v1/companyAvatarsFiles/:id | Delete tenant avatar |
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 can only be called by the users themselves. They are designed specific to the profile page.
Avatar upload workflow:
- User selects an image → crop with
react-easy-crop(install it, do not implement your own) - Convert cropped area to a Blob
- Upload to
POST {authBaseUrl}/bucket/userAvatars/uploadwith the access token - Get back the file metadata (id, accessKey)
- Construct the download URL:
{authBaseUrl}/bucket/userAvatars/download/key/{accessKey} - Call
PATCH {authBaseUrl}/v1/profilewith body{ avatar: downloadUrl }— no userId in the URL. The route is session-based; the BE resolves the target user from the access token.
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
axios({
method: 'GET',
url: `/v1/users/${userId}`,
data: {
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Profile API
This route is used by users to update their own profiles. The target user is always the session user — no userId is needed in the URL.
Rest Route
The updateProfile API REST controller can be triggered via the following route:
/v1/profile
Rest Request Parameters
The updateProfile api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| fullname | String | false | request.body?.[“fullname”] |
| avatar | String | false | request.body?.[“avatar”] |
| 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 |
REST Request To access the api you can use the REST controller with the path PATCH /v1/profile
axios({
method: 'PATCH',
url: '/v1/profile',
data: {
fullname:"String",
avatar:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"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. The target user is always the session user — no userId is needed in the URL.
Rest Route
The updateUserPassword API REST controller can be triggered via the following route:
/v1/profile/password
Rest Request Parameters
The updateUserPassword api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| oldPassword | String | true | request.body?.[“oldPassword”] |
| newPassword | String | true | request.body?.[“newPassword”] |
| 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/profile/password
axios({
method: 'PATCH',
url: '/v1/profile/password',
data: {
oldPassword:"String",
newPassword:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"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,
- 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.
- 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 own profiles. The target user is always the session user — no userId is needed in the URL.
Rest Route
The archiveProfile API REST controller can be triggered via the following route:
/v1/profile
Rest Request Parameters
The archiveProfile api has got no request parameters.
REST Request To access the api you can use the REST controller with the path DELETE /v1/profile
axios({
method: 'DELETE',
url: '/v1/profile',
data: {
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Tenant Profile Page (Tenant Manager)
In multi-tenant projects, also build a tenant profile page for tenantOwner and tenantAdmin roles.
This page allows these roles to view/update tenant standard and custom properties.
Use tenant-scoped profile APIs:
- Read current tenant profile:
getCompanyProfile(/companyprofile) - Update current tenant profile:
updateCompany(send tenant header and use current tenant id as route param)
For SaaS-level tenant management pages (superAdmin, saasAdmin, saasUser), use:
getCompanyAccountlistCompaniesAccounts
Do not use deprecated tenant APIs such as getCompanyByCodename or listRegisteredCompanies.
Get Companyprofile API
Get tenant profile information in tenant level. A private route for tenantOwner and tenantAdmin.
Rest Route
The getCompanyProfile API REST controller can be triggered via the following route:
/v1/companyprofile
Rest Request Parameters
The getCompanyProfile api has got no request parameters.
REST Request To access the api you can use the REST controller with the path GET /v1/companyprofile
axios({
method: 'GET',
url: '/v1/companyprofile',
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Company API
Update a company by id. An admin route which can be called by admins or tenant owners.
Rest Route
The updateCompany API REST controller can be triggered via the following route:
/v1/companies/:companyId
Rest Request Parameters
The updateCompany api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companyId | ID | true | request.params?.[“companyId”] |
| name | String | false | request.body?.[“name”] |
| fullname | String | false | request.body?.[“fullname”] |
| avatar | String | false | request.body?.[“avatar”] |
| industry | String | false | request.body?.[“industry”] |
| companySize | String | false | request.body?.[“companySize”] |
| companyId : This id paremeter is used to select the required data object that will be updated | |||
| name : A string value to represent one word name of the company | |||
| fullname : A string value to represent the fullname of the company | |||
| avatar : A string value represent the url of the company avatar. Keep null for random avatar. | |||
| industry : The industry the company operates in (e.g., Technology, Healthcare, Finance, etc.) | |||
| companySize : The size of the company (e.g., 1-10, 11-50, 51-200, etc.) |
REST Request To access the api you can use the REST controller with the path PATCH /v1/companies/:companyId
axios({
method: 'PATCH',
url: `/v1/companies/${companyId}`,
data: {
name:"String",
fullname:"String",
avatar:"String",
industry:"String",
companySize:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companyaccount API
Get tenant account information by id. A private SaaS-level route for superAdmin, saasAdmin and saasUser.
Rest Route
The getCompanyAccount API REST controller can be triggered via the following route:
/v1/companyaccounts/:companyId
Rest Request Parameters
The getCompanyAccount api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| companyId | ID | true | request.params?.[“companyId”] |
| companyId : The id of the company account to fetch |
REST Request To access the api you can use the REST controller with the path GET /v1/companyaccounts/:companyId
axios({
method: 'GET',
url: `/v1/companyaccounts/${companyId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Companiesaccounts API
List tenant accounts in SaaS level for superAdmin, saasAdmin and saasUser.
Rest Route
The listCompaniesAccounts API REST controller can be triggered via the following route:
/v1/companyaccounts
Rest Request Parameters
Filter Parameters
The listCompaniesAccounts api supports 5 optional filter parameters for filtering list results:
name (String): A string value to represent one word name of the company
- Single (partial match, case-insensitive):
?name=<value> - Multiple:
?name=<value1>&name=<value2> - Null:
?name=null
codename (String): A string value to represent a unique code name for the company which is generated automatically using name
- Single (partial match, case-insensitive):
?codename=<value> - Multiple:
?codename=<value1>&codename=<value2> - Null:
?codename=null
fullname (String): A string value to represent the fullname of the company
- Single (partial match, case-insensitive):
?fullname=<value> - Multiple:
?fullname=<value1>&fullname=<value2> - Null:
?fullname=null
avatar (String): A string value represent the url of the company avatar. Keep null for random avatar.
- Single (partial match, case-insensitive):
?avatar=<value> - Multiple:
?avatar=<value1>&avatar=<value2> - Null:
?avatar=null
ownerId (ID): An ID value to represent the user id of company owner who created the tenant
- Single:
?ownerId=<value> - Multiple:
?ownerId=<value1>&ownerId=<value2> - Null:
?ownerId=null
REST Request To access the api you can use the REST controller with the path GET /v1/companyaccounts
axios({
method: 'GET',
url: '/v1/companyaccounts',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// name: '<value>' // Filter by name
// codename: '<value>' // Filter by codename
// fullname: '<value>' // Filter by fullname
// avatar: '<value>' // Filter by avatar
// ownerId: '<value>' // Filter by ownerId
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companies",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"companies": [
{
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
After you complete this step, please ensure you have not made the following common mistakes:
- Avatar uploads go to the auth service’s database bucket endpoints (
/bucket/userAvatars/upload), not to an external bucket service. Use the sameaccessToken(Bearer header) for both auth APIs and avatar bucket uploads — no bucket-specific tokens are needed. - 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.
- On the profile page, fetch the latest user data from the service using
getUser. The/currentuserAPI is session-stored data; the latest data is in the database. - When you upload the avatar image on the profile page, use the returned download URL as the user’s
avatarproperty 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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - User Management
This document is the 2nd part of a REST API guide for the workforceos 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.
Scope reminder — keep admin features focused.
A standard dynamic SaaS app typically ships a basic admin section with: user list, view single user, create user, edit user, change role, reset password by admin, delete user. Build those.
Skip these unless the project’s scope explicitly asks for them:
- Audit log / activity history pages (
useUserHistoryhook is available, but don’t auto-build a dedicated screen)- Active-session management UI (
useUserSessions/useDeleteUserSessionare available, skip the dedicated screen)- Anything labeled “(OPTIONAL)” further down
The hooks for these stay documented for reference — the rule is “available, not auto-built”. If the scope says “admin can see user activity”, you can wire them. Otherwise leave them out and keep the admin section lean.
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://workforceos.prw.mindbricks.com/auth-api - Staging:
https://workforceos-stage.mindbricks.co/auth-api - Production:
https://workforceos.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, saasAdmin, tenantOwner, tenantAdmin
Scope
Auth service provides following feature for user management in workforceos application.
These features are already handled in the previous part.
- User Registration
- User Authentication
- Password Reset
- Email (and/or) Mobile Verification
- 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:
{
"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.
{
"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. -
saasAdmin: 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. -
tenantOwner: The first creator of the company tenant. This user is automatically gets this role when they first created the tenant. They have all authroization in the scope of their company tenant. This role can’t be assigned or unassgined. Tenant owner user can not be deleted unless the tenant is deleted. -
tenantAdmin: The role that can be assigned to any user by the tenant owner. This role includes most permissions that tenant owner have, but tenant admins can’t assign tenant admin roles, can’t unassign tenant admin roles, can’t delete other users who have tenant admin role. -
tenantUser: The standard role that is assgined to every user when first created or registered. This role doesnt have any privilages and can access to their own data or public data.
The roles object is a hardcoded object in the generated code, and it contains the following roles:
{
"superAdmin": "'superAdmin'",
"saasAdmin": "'saasAdmin'",
"tenantOwner": "'tenantOwner'",
"tenantAdmin": "'tenantAdmin'",
"tenantUser": "'tenantUser'"
}
Each user may have only one role, and it is given in /login , /currentuser or /users/:userId response as follows
{
// ...
"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=<value> - Multiple:
?email=<value1>&email=<value2> - Null:
?email=null
fullname (String): A string value to represent the fullname of the user
- Single (partial match, case-insensitive):
?fullname=<value> - Multiple:
?fullname=<value1>&fullname=<value2> - Null:
?fullname=null
roleId (String): A string value to represent the roleId of the user.
- Single (partial match, case-insensitive):
?roleId=<value> - Multiple:
?roleId=<value1>&roleId=<value2> - Null:
?roleId=null
REST Request To access the api you can use the REST controller with the path GET /v1/users
axios({
method: 'GET',
url: '/v1/users',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// email: '<value>' // Filter by email
// fullname: '<value>' // Filter by fullname
// roleId: '<value>' // Filter by roleId
}
});
REST Response
{
"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",
"companyId": "ID",
"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=<value> - Multiple:
?roleId=<value1>&roleId=<value2> - Null:
?roleId=null
REST Request To access the api you can use the REST controller with the path GET /v1/searchusers
axios({
method: 'GET',
url: '/v1/searchusers',
data: {
},
params: {
keyword:'"String"',
// Filter parameters (see Filter Parameters section above)
// roleId: '<value>' // Filter by roleId
}
});
REST Response
{
"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",
"companyId": "ID",
"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.
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 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| avatar | String | false | request.body?.[“avatar”] |
| roleId | String | false | request.body?.[“roleId”] |
| emailVerified | Boolean | false | request.body?.[“emailVerified”] |
| 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. | |||
| roleId : The role to assign to the new user. Defaults to ‘tenantUser’ when omitted. | |||
| emailVerified : Pre-verify the user’s email at admin-create time. Defaults to false (the user must run the public verify-email flow to flip this to true). | |||
| 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
axios({
method: 'POST',
url: '/v1/users',
data: {
avatar:"String",
roleId:"String",
emailVerified:"Boolean",
email:"String",
password:"String",
fullname:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"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:
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 <img> 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 updateUserapi. 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 3 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”] |
| 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 |
REST Request To access the api you can use the REST controller with the path PATCH /v1/users/:userId
axios({
method: 'PATCH',
url: `/v1/users/${userId}`,
data: {
fullname:"String",
avatar:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
For role updates there are some rules.
- Superadmin role can not be unassigned even by superadmin.
- Admin roles can be assgined or unassgined only by superadmin.
- All other roles can be assigned and unassgined by admins and superadmin.
For password updates there are some rules.
- Superadmin and admin passwords can be updated only by superadmin.
- 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 tenantUser when a tenant user is registered. A tenant user’s role can be updated by tenantAdmin / tenantOwner, while saas user’s role is updated by superAdmin or saasAdmin
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
axios({
method: 'PATCH',
url: `/v1/userrole/${userId}`,
data: {
roleId:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"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
axios({
method: 'PATCH',
url: `/v1/userpasswordbyadmin/${userId}`,
data: {
password:"String",
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Deleting Users
Deleting users is possible in certain conditions.
- SuperAdmin can not be deleted.
- Admins can be deleted by only superadmin.
- 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
axios({
method: 'DELETE',
url: `/v1/users/${userId}`,
data: {
},
params: {
}
});
REST Response
{
"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",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
User Group Management
This application backend provides user groups with two data tables, UserGroup and UserGroupMember, so the admin dashboard UI should support user group creating/deleting and adding or removing member users to the groups.
Design a minimal and fancy user group management console where we can manage the groups and their members. The user groups may be in a main list and when selected a right drawer can show the members of the group, and at the bottom of the drawer there can be a user search area to select the user to be added to the group. For user searching use the user search api and make a call to the api in each character added to the search edit box.
To manage user groups and members, use the related apis below.
Create Usergroup API
This route is used by admin roles to create a new usergroup manually from admin panels
Rest Route
The createUserGroup API REST controller can be triggered via the following route:
/v1/usergroups
Rest Request Parameters
The createUserGroup api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| avatar | String | false | request.body?.[“avatar”] |
| groupName | String | true | request.body?.[“groupName”] |
| avatar : A string value to represent the groups icon. | |||
| groupName : A string value to represent the group name. |
REST Request To access the api you can use the REST controller with the path POST /v1/usergroups
axios({
method: 'POST',
url: '/v1/usergroups',
data: {
avatar:"String",
groupName:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroup",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"userGroup": {
"id": "ID",
"groupName": "String",
"avatar": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Usergroup API
This route is used by admin to update user groups.
Rest Route
The updateUserGroup API REST controller can be triggered via the following route:
/v1/usergroups/:userGroupId
Rest Request Parameters
The updateUserGroup api has got 3 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| userGroupId | ID | true | request.params?.[“userGroupId”] |
| groupName | String | false | request.body?.[“groupName”] |
| avatar | String | false | request.body?.[“avatar”] |
| userGroupId : This id paremeter is used to select the required data object that will be updated | |||
| groupName : A string value to represent the group name. | |||
| avatar : A string value to represent the groups icon. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/usergroups/:userGroupId
axios({
method: 'PATCH',
url: `/v1/usergroups/${userGroupId}`,
data: {
groupName:"String",
avatar:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroup",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"userGroup": {
"id": "ID",
"groupName": "String",
"avatar": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Usergroup API
This route is used by admin to delete a user group.
Rest Route
The deleteUserGroup API REST controller can be triggered via the following route:
/v1/usergroups/:userGroupId
Rest Request Parameters
The deleteUserGroup api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| userGroupId | ID | true | request.params?.[“userGroupId”] |
| userGroupId : 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/usergroups/:userGroupId
axios({
method: 'DELETE',
url: `/v1/usergroups/${userGroupId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroup",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"userGroup": {
"id": "ID",
"groupName": "String",
"avatar": "String",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Usergroup API
This is a public route to get the user group information.
Rest Route
The getUserGroup API REST controller can be triggered via the following route:
/v1/usergroups/:userGroupId
Rest Request Parameters
The getUserGroup api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| userGroupId | ID | true | request.params?.[“userGroupId”] |
| userGroupId : 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/usergroups/:userGroupId
axios({
method: 'GET',
url: `/v1/usergroups/${userGroupId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroup",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"userGroup": {
"id": "ID",
"groupName": "String",
"avatar": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Usergroups API
This is a public route to get the list of groups.
Rest Route
The listUserGroups API REST controller can be triggered via the following route:
/v1/usergroups
Rest Request Parameters
Filter Parameters
The listUserGroups api supports 2 optional filter parameters for filtering list results:
groupName (String): A string value to represent the group name.
- Single (partial match, case-insensitive):
?groupName=<value> - Multiple:
?groupName=<value1>&groupName=<value2> - Null:
?groupName=null
avatar (String): A string value to represent the groups icon.
- Single (partial match, case-insensitive):
?avatar=<value> - Multiple:
?avatar=<value1>&avatar=<value2> - Null:
?avatar=null
REST Request To access the api you can use the REST controller with the path GET /v1/usergroups
axios({
method: 'GET',
url: '/v1/usergroups',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// groupName: '<value>' // Filter by groupName
// avatar: '<value>' // Filter by avatar
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroups",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"userGroups": [
{
"id": "ID",
"groupName": "String",
"avatar": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
A user group member is stored in the db with groupId and userId fields. The id field identifies the membership, so when removing a user from a group, the membership record (UserGroupMember) should be deleted by this id. The UserGroupMember record also has an ownerId which is automatically added to teh record from the session’s userId. This ownerId identifes the admin user who added the user to the group.
Create Usergroupmember API
This route is used by admin roles to add a user to a group.
Rest Route
The createUserGroupMember API REST controller can be triggered via the following route:
/v1/usergroupmembers
Rest Request Parameters
The createUserGroupMember api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| groupId | ID | true | request.body?.[“groupId”] |
| userId | ID | true | request.body?.[“userId”] |
| groupId : An ID value to represent the group that the user is asssigned as a memeber to. | |||
| userId : An ID value to represent the user that is assgined as a member to the group. |
REST Request To access the api you can use the REST controller with the path POST /v1/usergroupmembers
axios({
method: 'POST',
url: '/v1/usergroupmembers',
data: {
groupId:"ID",
userId:"ID",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroupMember",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"userGroupMember": {
"id": "ID",
"groupId": "ID",
"userId": "ID",
"ownerId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Usergroupmember API
This route is used by admin to delete a member from a group.
Rest Route
The deleteUserGroupMember API REST controller can be triggered via the following route:
/v1/usergroupmembers/:userGroupMemberId
Rest Request Parameters
The deleteUserGroupMember api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| userGroupMemberId | ID | true | request.params?.[“userGroupMemberId”] |
| userGroupMemberId : 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/usergroupmembers/:userGroupMemberId
axios({
method: 'DELETE',
url: `/v1/usergroupmembers/${userGroupMemberId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroupMember",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"userGroupMember": {
"id": "ID",
"groupId": "ID",
"userId": "ID",
"ownerId": "ID",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Usergroupmembers API
This is a public route to get the list of group members of a group.
Rest Route
The listUserGroupMembers API REST controller can be triggered via the following route:
/v1/listusergroupmembers/:groupId
Rest Request Parameters
The listUserGroupMembers api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| groupId | ID | true | request.params?.[“groupId”] |
| groupId : An ID value to represent the group that the user is asssigned as a memeber to… The parameter is used to query data. |
Filter Parameters
The listUserGroupMembers api supports 2 optional filter parameters for filtering list results:
userId (ID): An ID value to represent the user that is assgined as a member to the group.
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
ownerId (ID): An ID value to represent the admin user who assgined the member.
- Single:
?ownerId=<value> - Multiple:
?ownerId=<value1>&ownerId=<value2> - Null:
?ownerId=null
REST Request To access the api you can use the REST controller with the path GET /v1/listusergroupmembers/:groupId
axios({
method: 'GET',
url: `/v1/listusergroupmembers/${groupId}`,
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '<value>' // Filter by userId
// ownerId: '<value>' // Filter by ownerId
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroupMembers",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"userGroupMembers": [
{
"id": "ID",
"groupId": "ID",
"userId": "ID",
"ownerId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": {
"email": "String",
"fullname": "String",
"avatar": "String"
}
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
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,filefield) - Download:
GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}(public, no auth needed) - Allowed: image/png, image/jpeg, image/webp, image/gif (max 5 MB)
Company Avatar Bucket:
- Upload:
POST {authBaseUrl}/bucket/companyAvatars/upload - Download:
GET {authBaseUrl}/bucket/companyAvatars/download/key/{accessKey} - Same configuration as user avatars.
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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - MCP BFF Integration
This document is a part of a REST API guide for the workforceos 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 Workforceos 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
accessTokeninto 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://workforceos.prw.mindbricks.com/mcpbff-api - Staging:
https://workforceos-stage.mindbricks.co/mcpbff-api - Production:
https://workforceos.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:
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
};
For multi-tenant access, include the tenant codename header:
headers['mbx-company-codename'] = companyCodename;
Resolve companyCodename from frontend routing context (URL prefix in preview/test, subdomain in production) and forward it in all MCP BFF calls.
Frontend URL/subdomain is only for tenant selection; backend tenant targeting must always be done with this header.
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.
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:
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: <eventType>\n
data: <JSON>\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.
{
"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.
{ "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.
{ "tool": "currentuser" }
tool_executing — Tool is now executing with these arguments. Use this to display what the tool is doing.
{ "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.
{
"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:
{
"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.
{
"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.
{ "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:
text— Append to the last segment if it is a text segment; otherwise push a new text segment.tool_start— Push a new tool segment (status:running). This “cuts” the current text segment — any furthertextevents after the tool completes will start a new text segment.tool_executing— Update the current tool segment withargs.tool_result— Update the current tool segment withresult,success,error. Check for__frontendAction.- After
tool_result, the nexttextevent 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:
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)
// 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:
function AssistantMessageBubble({ segments }) {
return (
<div className="assistant-bubble">
{segments.map((segment, i) => {
if (segment.type === 'text') {
return <MarkdownRenderer key={i} content={segment.content} />;
}
if (segment.type === 'tool') {
if (segment.frontendAction) {
return <ActionCard key={i} action={segment.frontendAction} />;
}
return <ToolCard key={i} segment={segment} />;
}
return null;
})}
</div>
);
}
function ToolCard({ segment }) {
const isRunning = segment.status === 'running';
const isError = segment.status === 'error';
return (
<div className={`tool-card ${segment.status}`}>
<div className="tool-header">
{isRunning && <Spinner size="sm" />}
<span className="tool-name">{segment.tool}</span>
{!isRunning && (isError ? <ErrorIcon /> : <CheckIcon />)}
</div>
{segment.args && (
<CollapsibleSection label="Arguments">
<pre>{JSON.stringify(segment.args, null, 2)}</pre>
</CollapsibleSection>
)}
{segment.result && (
<CollapsibleSection label="Result" defaultCollapsed>
<pre>{JSON.stringify(segment.result, null, 2)}</pre>
</CollapsibleSection>
)}
{segment.error && <div className="tool-error">{segment.error}</div>}
</div>
);
}
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:
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 |
secret |
SecretActionCard |
Renders a secret field as text, barcode, or QR code |
QR Code Action (type: "qrcode")
Triggered by the showQrCode MCP tool. Renders a QR code card from any string value.
{
"__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/columnsviewType: "gallery"as image-first cards
{
"__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.
{
"__frontendAction": {
"type": "payment",
"orderId": "uuid",
"orderType": "order",
"serviceName": "commerce",
"amount": 99.99,
"currency": "USD",
"description": "Order #abc123"
}
}
Secret Action (type: "secret")
Triggered by the showSecretFieldInFrontEnd MCP tool. Renders the secret value securely.
{
"__frontendAction": {
"type": "secret",
"fieldName": "apiKey",
"fieldLabel": "API Key",
"value": "actual-secret-value",
"renderType": "asText",
"serviceName": "commerce",
"objectName": "coupon",
"modelName": "Coupon",
"recordId": "uuid"
}
}
The renderType determines how the value is displayed:
"asText"— Plain text with copy-to-clipboard button"asBarcode"— Barcode image (usingreact-barcode)"asQrCode"— QR code image (usingreact-qr-code)
The AI chooses the renderType based on what the user asks for (e.g., “show me the QR code” → asQrCode, “let me see the key” → asText). If the user doesn’t specify, the AI should ask them how they’d like to see it.
The card auto-hides the value after 2 minutes for security.
Conversation Management
// 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
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
const response = await fetch(`${mcpBffUrl}/api/tools/service/commerce`, { headers });
const { tools } = await response.json();
POST /api/tools/call — Call a Tool Directly
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
const status = await fetch(`${mcpBffUrl}/api/tools/status`, { headers });
// Returns health of each MCP service connection
POST /api/tools/refresh — Reconnect Services
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 workforceos_).
const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers });
// ["workforceos_products", "workforceos_orders", ...]
POST /api/elastic/:indexName/rawsearch — Raw Elasticsearch Query
Execute a raw Elasticsearch query on a specific index.
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 workforceos_ 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.
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.
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).
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.
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
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=ERRORservice— Filter by service namesearch— Search in subject and messagefrom/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.
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, ... }
});
Secret Field Management via MCP
Some data objects contain secret properties — sensitive values like API keys, QR codes, or tokens that are protected from AI model exposure.
How It Works
- When the AI retrieves data via MCP tools (GET/LIST), secret fields are masked with
***in the response. The AI never sees the actual values. - Each masked record includes a
__proxyCode— a temporary token proving the user was authorized to access that record. - When the user asks to see a secret, the AI calls
showSecretFieldInFrontEndwith theproxyCodeand desired render type. - The tool returns a
__frontendActionwithtype: "secret"containing the actual value. - The frontend renders the value in a
SecretActionCard(text, barcode, or QR code) with auto-hide.
Objects with Secret Fields
- EmployeeProfile (
employeeProfile):notes - EmployeeDocument (
employeeProfile):documentUrl
Example MCP Flows
User specifies render type:
User: "Show me the QR code for coupon #abc"
AI → calls getCoupon(id: "abc")
← receives { coupon: { id: "abc", code: "***", __proxyCode: "f7a3b2..." } }
AI → calls showSecretFieldInFrontEnd(proxyCode: "f7a3b2...", fieldName: "code", renderType: "asQrCode")
← receives { __frontendAction: { type: "secret", value: "COUPON-XYZ-123", renderType: "asQrCode", ... } }
Frontend → renders SecretActionCard with QR code image
User does not specify — AI asks first:
User: "Show me the secret code for coupon #abc"
AI → calls getCoupon(id: "abc")
← receives { coupon: { id: "abc", code: "***", __proxyCode: "f7a3b2..." } }
AI → "How would you like to see the code? I can show it as plain text, a barcode, or a QR code."
User: "As a barcode please"
AI → calls showSecretFieldInFrontEnd(proxyCode: "f7a3b2...", fieldName: "code", renderType: "asBarcode")
← receives { __frontendAction: { type: "secret", value: "COUPON-XYZ-123", renderType: "asBarcode", ... } }
Frontend → renders SecretActionCard with barcode image
Frontend Implementation
In your chat UI, handle the secret action type in the ActionCard dispatcher:
function ActionCard({ action }) {
switch (action.type) {
case 'secret':
return <SecretActionCard action={action} />;
// ... other action types
}
}
The SecretActionCard component renders based on renderType:
- asText: Monospace text with copy button, auto-hides after 2 minutes
- asBarcode: Barcode image (requires
react-barcodepackage) - asQrCode: QR code image (requires
react-qr-codepackage)
For data tables and detail views (outside the chat), secret fields should be masked by default with an eye toggle button to reveal the value.
Available Services
The MCP BFF connects to the following backend services:
| Service | Description |
|---|---|
auth |
Authentication, user management, sessions |
employeeProfile |
Manages extended employee profile data, employment/tax details, and employee-related documents/certifications for each company. Extends user identities with HR, department, and compliance info. Allows managers and admins to review employee profiles and documents… |
scheduleManagement |
Microservice managing shift scheduling, shift templates, assignment of users/departments to shifts, and schedule conflict detection for WorkforceOS. |
attendanceManagement |
Handles employee attendance logging (check-in/out), attendance rules (lateness/absence/early-leave), real-time & historical logs, and publishes notification events. Enforces company data isolation, strict record uniqueness, and one-per-shift attendance rule. |
taskManagement |
Handles creation, assignment, update, and tracking of tasks tied to employees, shifts, or departments. Supports admins/managers assigning tasks; employees viewing and completing tasks; accountability tracking. Exposes APIs for creating, updating, deleting, and listing tasks with data enrichment. Data is .company-tenant-scoped… |
leaveManagement |
Handles employee leave/absence requests, review/approval workflows, and automatic integration with shift assignments, ensuring company data isolation and leave history access for employees and managers/admins. |
payrollReporting |
Handles payroll report records for employees based on calculated hours, overtime, absences from attendance/leave. Provides summary views by user/period/department, allows payment status entry (not processing). Employees can view their own reports. Company tenant scoped and RBAC-enforced. |
announcementManagement |
Handles company-wide and department-specific announcements, supporting scheduled or immediate delivery. Enables admins/managers to create, edit, and manage rich-text announcements, assign audience (all/company/department/users), and triggers events for notification delivery. Employees see relevant announcements in history/detail. Fully tenant-scoped. |
aiWorkforceAnalytics |
Microservice for computing and delivering AI-powered workforce analytics (e.g., shift optimization, absenteeism insights, staffing trends) for eligible (subscribed) companies. Handles insight calculation, storage, and secure distribution to authorized users. Publishes insight alerts/events for notifications. Strictly enforces company data isolation and subscription gating on all features. |
subscriptionManagement |
Manages company AI subscriptions through Stripe payments. Companies must pay via Stripe to activate AI features—no manual subscription creation allowed. Handles the full Stripe payment lifecycle: checkout, payment confirmation, activation, and cancellation. The subscription status is entirely driven by Stripe webhook events. SuperAdmin/saasAdmin bypass payment for platform management. |
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:
// 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://workforceos.prw.mindbricks.com/mcpbff-api/mcp |
| Staging | https://workforceos-stage.mindbricks.co/mcpbff-api/mcp |
| Production | https://workforceos.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:
-
Endpoint URL — Display the MCP endpoint URL for the current environment with a copy-to-clipboard button.
-
Ready-to-Copy Configs — Show copy-to-clipboard config snippets for popular tools:
Cursor (
.cursor/mcp.json):{ "mcpServers": { "workforceos": { "url": "https://workforceos.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } }Claude Desktop (
claude_desktop_config.json):{ "mcpServers": { "workforceos": { "url": "https://workforceos.prw.mindbricks.com/mcpbff-api/mcp", "headers": { "Authorization": "Bearer your_access_token_here" } } } } -
Auth Note — Note that users should replace
your_access_token_herewith a valid JWT access token from the login API. -
OAuth Note — Display a note that OAuth authentication is not currently supported for MCP connections.
-
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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - EmployeeProfile Service
This document is a part of a REST API guide for the workforceos 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 employeeProfile
Service Access
EmployeeProfile service management is handled through service specific base urls.
EmployeeProfile 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 employeeProfile service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/employeeprofile-api - Staging:
https://workforceos-stage.mindbricks.co/employeeprofile-api - Production:
https://workforceos.mindbricks.co/employeeprofile-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to employeeProfile service.
Scope
EmployeeProfile Service Description
Manages extended employee profile data, employment/tax details, and employee-related documents/certifications for each company. Extends user identities with HR, department, and compliance info. Allows managers and admins to review employee profiles and documents…
EmployeeProfile service provides apis and business logic for following data objects in workforceos 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.
employeeProfile Data Object: Extended business-centric employee profile with employment, compensation, department, and management fields associated to an auth user. Enables company to track staff employment metadata, department, position, and assigned manager for full HR oversight.
employeeDocument Data Object: Document or certification attached to an employee profile. E.g., work permit, certification, or contract files.
EmployeeProfile Service Frontend Description By The Backend Architect
AI UX note: This microservice manages business-specific employee details beyond core user identity. For managers and admins, provide filtered views sortable by department, status, and position, with access to employee documents and notes. For employees, provide a secure, editable view of their own profile (with limits on updatable fields). Document detail views should show expiration and allow uploads (via file picker). Employee/manager selectors must use full names, roles, and departments for human-readable reference.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
EmployeeProfile Data Object
Extended business-centric employee profile with employment, compensation, department, and management fields associated to an auth user. Enables company to track staff employment metadata, department, position, and assigned manager for full HR oversight.
EmployeeProfile Data Object Frontend Description By The Backend Architect
AI UX note: Profile pages expose all fields except salary/notes to the employee (notes are manager/admin only). Department/position fields are read-only for employees. Employment start is always visible. Manager/admin users see all fields for company staff, with filtering by department/position/status.
EmployeeProfile Data Object Properties
EmployeeProfile 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 | Reference to the auth user for this employee profile. |
employmentStartDate |
Date | false | Yes | No | Employee’s official employment start date. |
position |
String | false | Yes | No | Employee’s job title or position |
contractType |
Enum | false | Yes | No | Type of employment contract for this employee. |
salary |
Double | false | No | No | Employee’s salary for reporting (managers/admins only). |
departmentId |
ID | false | No | No | Reference to the department (userGroup) this employee belongs to. |
managerId |
ID | false | No | No | ID of the assigned manager or supervisor (userId from auth:user). |
notes |
Text | false | No | Yes | Manager/admin internal notes (not visible to employees). |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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.
- contractType: [permanent, temporary, contract]
Relation Properties
userId departmentId managerId
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 sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
- departmentId: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- managerId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
userId employmentStartDate position contractType departmentId managerId companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
userId: ID has a filter named
userId -
employmentStartDate: Date has a filter named
employmentStartDate -
position: String has a filter named
position -
contractType: Enum has a filter named
contractType -
departmentId: ID has a filter named
departmentId -
managerId: ID has a filter named
managerId -
companyId: ID has a filter named
companyId
EmployeeDocument Data Object
Document or certification attached to an employee profile. E.g., work permit, certification, or contract files.
EmployeeDocument Data Object Frontend Description By The Backend Architect
AI UX note: Document upload is via file selector, storing the URL as documentUrl. The list and detail view show document type, validity/expiration if set, and allow download/view (if permitted). New documents can be added by managers/admins; employees can see their own docs only. Document list is ordered by validUntil desc, with expired docs visually flagged.
EmployeeDocument Data Object Properties
EmployeeDocument 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 |
|---|---|---|---|---|---|
employeeProfileId |
ID | false | Yes | No | Reference to the related employeeProfile record. |
documentType |
String | false | Yes | No | Type of document (e.g., ID, contract, certification). |
documentUrl |
String | false | Yes | Yes | URL to the file storage location or bucket for this document. |
validUntil |
Date | false | No | No | Expiration date of document, if applicable. Used for tracking compliance/renewal. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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
employeeProfileId documentType validUntil companyId
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.
-
employeeProfileId: ID has a filter named
employeeProfileId -
documentType: String has a filter named
documentType -
validUntil: Date has a filter named
validUntil -
companyId: ID has a filter named
companyId
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.
EmployeeProfile Default APIs
Display Label Property: position — 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 | createEmployeeProfile |
/v1/employeeprofiles |
Yes |
| Update | updateEmployeeProfile |
/v1/employeeprofiles/:employeeProfileId |
Yes |
| Delete | deleteEmployeeProfile |
/v1/employeeprofiles/:employeeProfileId |
Auto |
| Get | getEmployeeProfile |
/v1/employeeprofiles/:employeeProfileId |
Yes |
| List | listEmployeeProfiles |
/v1/employeeprofiles |
Yes |
EmployeeDocument Default APIs
Display Label Property: documentType — 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 | createEmployeeDocument |
/v1/employeedocuments |
Yes |
| Update | updateEmployeeDocument |
/v1/employeedocuments/:employeeDocumentId |
Yes |
| Delete | deleteEmployeeDocument |
/v1/employeedocuments/:employeeDocumentId |
Auto |
| Get | getEmployeeDocument |
/v1/employeedocuments/:employeeDocumentId |
Yes |
| List | listEmployeeDocuments |
/v1/employeedocuments |
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.
Secret Field Management
Some data objects in the employeeProfile service contain secret properties — sensitive values like API keys, QR codes, or tokens that must be handled with care.
How Secret Fields Work
-
In API Responses: Secret fields are returned with their actual values in normal REST API responses (the user’s own token authorizes access). The frontend should mask these values by default and only reveal them on user action (e.g., clicking an “eye” toggle button).
-
In MCP/AI Responses: Secret fields are automatically masked with
***in MCP tool responses. The AI model never sees the actual values. Each record that contains masked fields includes a__proxyCode— a temporary authorization token. -
Revealing Secrets via MCP: When a user asks the AI to show a secret field, the AI uses the
showSecretFieldInFrontEndMCP tool with:proxyCode— from the GET/LIST response (proves user authorization)fieldName— the secret property to revealrenderType—"asText","asBarcode", or"asQrCode"
The AI decides the
renderTypebased on the user’s request (e.g., “show me the QR code” →asQrCode). If the user doesn’t specify a format, the AI should ask the user how they’d like to see it before calling the tool. -
Frontend Rendering: The tool returns a
__frontendActionwithtype: "secret"that the chat UI renders as aSecretActionCard. This card displays the actual value as text (with copy button), barcode, or QR code, and auto-hides after a timeout for security.
Secret Properties by Data Object
EmployeeProfile: notes
EmployeeDocument: documentUrl
Frontend Implementation Guidelines
- Data tables / detail views: Mask secret fields with
***or••••••by default. Show an eye toggle button that reveals the value on click. - Forms: Use password-type inputs for secret fields. Allow the user to toggle visibility.
- Chat UI: The
SecretActionCardcomponent handles rendering when the AI reveals a secret viashowSecretFieldInFrontEnd. - Security: Never log secret values in the browser console. Consider auto-hiding revealed values after a timeout.
MCP Tool: showSecretFieldInFrontEnd
Tool Name: showSecretFieldInFrontEnd
Parameters:
- proxyCode (string, required): The __proxyCode from a previous GET/LIST response
- fieldName (string, required): One of: notes, documentUrl
- renderType (enum, required): "asText" | "asBarcode" | "asQrCode"
Response: __frontendAction with type "secret" containing the actual value
API Reference
Create Employeeprofile API
[Default create API] — This is the designated default create API for the employeeProfile data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Creates a new employee profile for a user in the company.
Rest Route
The createEmployeeProfile API REST controller can be triggered via the following route:
/v1/employeeprofiles
Rest Request Parameters
The createEmployeeProfile api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| userId | ID | true | request.body?.[“userId”] |
| employmentStartDate | Date | true | request.body?.[“employmentStartDate”] |
| position | String | true | request.body?.[“position”] |
| contractType | Enum | true | request.body?.[“contractType”] |
| salary | Double | false | request.body?.[“salary”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| managerId | ID | false | request.body?.[“managerId”] |
| notes | Text | false | request.body?.[“notes”] |
| userId : Reference to the auth user for this employee profile. | |||
| employmentStartDate : Employee’s official employment start date. | |||
| position : Employee’s job title or position | |||
| contractType : Type of employment contract for this employee. | |||
| salary : Employee’s salary for reporting (managers/admins only). | |||
| departmentId : Reference to the department (userGroup) this employee belongs to. | |||
| managerId : ID of the assigned manager or supervisor (userId from auth:user). | |||
| notes : Manager/admin internal notes (not visible to employees). |
REST Request To access the api you can use the REST controller with the path POST /v1/employeeprofiles
axios({
method: 'POST',
url: '/v1/employeeprofiles',
data: {
userId:"ID",
employmentStartDate:"Date",
position:"String",
contractType:"Enum",
salary:"Double",
departmentId:"ID",
managerId:"ID",
notes:"Text",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeProfile",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"employeeProfile": {
"id": "ID",
"userId": "ID",
"employmentStartDate": "Date",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer",
"salary": "Double",
"departmentId": "ID",
"managerId": "ID",
"notes": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Employeeprofile API
[Default update API] — This is the designated default update API for the employeeProfile data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Update the employee profile for a given user. Employees can only update their own profile; admins/managers can update any profile in the same company.
Rest Route
The updateEmployeeProfile API REST controller can be triggered via the following route:
/v1/employeeprofiles/:employeeProfileId
Rest Request Parameters
The updateEmployeeProfile api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeProfileId | ID | true | request.params?.[“employeeProfileId”] |
| employmentStartDate | Date | false | request.body?.[“employmentStartDate”] |
| position | String | false | request.body?.[“position”] |
| contractType | Enum | false | request.body?.[“contractType”] |
| salary | Double | false | request.body?.[“salary”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| managerId | ID | false | request.body?.[“managerId”] |
| notes | Text | false | request.body?.[“notes”] |
| employeeProfileId : This id paremeter is used to select the required data object that will be updated | |||
| employmentStartDate : Employee’s official employment start date. | |||
| position : Employee’s job title or position | |||
| contractType : Type of employment contract for this employee. | |||
| salary : Employee’s salary for reporting (managers/admins only). | |||
| departmentId : Reference to the department (userGroup) this employee belongs to. | |||
| managerId : ID of the assigned manager or supervisor (userId from auth:user). | |||
| notes : Manager/admin internal notes (not visible to employees). |
REST Request To access the api you can use the REST controller with the path PATCH /v1/employeeprofiles/:employeeProfileId
axios({
method: 'PATCH',
url: `/v1/employeeprofiles/${employeeProfileId}`,
data: {
employmentStartDate:"Date",
position:"String",
contractType:"Enum",
salary:"Double",
departmentId:"ID",
managerId:"ID",
notes:"Text",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeProfile",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"employeeProfile": {
"id": "ID",
"userId": "ID",
"employmentStartDate": "Date",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer",
"salary": "Double",
"departmentId": "ID",
"managerId": "ID",
"notes": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Employeeprofile API
[Default get API] — This is the designated default get API for the employeeProfile data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get detailed employee profile info, with enriched user, department, and manager references. Employees may view their own record; admins/managers can view any profile in company.
Rest Route
The getEmployeeProfile API REST controller can be triggered via the following route:
/v1/employeeprofiles/:employeeProfileId
Rest Request Parameters
The getEmployeeProfile api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeProfileId | ID | true | request.params?.[“employeeProfileId”] |
| employeeProfileId : 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/employeeprofiles/:employeeProfileId
axios({
method: 'GET',
url: `/v1/employeeprofiles/${employeeProfileId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeProfile",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"employeeProfile": {
"id": "ID",
"userId": "ID",
"employmentStartDate": "Date",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer",
"salary": "Double",
"departmentId": "ID",
"managerId": "ID",
"notes": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": {
"email": "String",
"fullname": "String",
"avatar": "String"
},
"manager": {
"email": "String",
"fullname": "String",
"avatar": "String"
}
}
}
List Employeeprofiles API
[Default list API] — This is the designated default list API for the employeeProfile data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List all employee profiles for a company, filterable by department, position, contract type, and manager.
Rest Route
The listEmployeeProfiles API REST controller can be triggered via the following route:
/v1/employeeprofiles
Rest Request Parameters
Filter Parameters
The listEmployeeProfiles api supports 4 optional filter parameters for filtering list results:
userId (ID): Reference to the auth user for this employee profile.
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
employmentStartDate (Date): Employee’s official employment start date.
- Single date:
?employmentStartDate=2024-01-15 - Multiple dates:
?employmentStartDate=2024-01-15&employmentStartDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?employmentStartDate=null
departmentId (ID): Reference to the department (userGroup) this employee belongs to.
- Single:
?departmentId=<value> - Multiple:
?departmentId=<value1>&departmentId=<value2> - Null:
?departmentId=null
managerId (ID): ID of the assigned manager or supervisor (userId from auth:user).
- Single:
?managerId=<value> - Multiple:
?managerId=<value1>&managerId=<value2> - Null:
?managerId=null
REST Request To access the api you can use the REST controller with the path GET /v1/employeeprofiles
axios({
method: 'GET',
url: '/v1/employeeprofiles',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '<value>' // Filter by userId
// employmentStartDate: '<value>' // Filter by employmentStartDate
// departmentId: '<value>' // Filter by departmentId
// managerId: '<value>' // Filter by managerId
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeProfiles",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"employeeProfiles": [
{
"id": "ID",
"userId": "ID",
"employmentStartDate": "Date",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer",
"salary": "Double",
"departmentId": "ID",
"managerId": "ID",
"notes": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"department": [
null,
null,
null
],
"manager": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Create Employeedocument API
[Default create API] — This is the designated default create API for the employeeDocument data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Create a new document entry for an employee profile.
Rest Route
The createEmployeeDocument API REST controller can be triggered via the following route:
/v1/employeedocuments
Rest Request Parameters
The createEmployeeDocument api has got 4 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeProfileId | ID | true | request.body?.[“employeeProfileId”] |
| documentType | String | true | request.body?.[“documentType”] |
| documentUrl | String | true | request.body?.[“documentUrl”] |
| validUntil | Date | false | request.body?.[“validUntil”] |
| employeeProfileId : Reference to the related employeeProfile record. | |||
| documentType : Type of document (e.g., ID, contract, certification). | |||
| documentUrl : URL to the file storage location or bucket for this document. | |||
| validUntil : Expiration date of document, if applicable. Used for tracking compliance/renewal. |
REST Request To access the api you can use the REST controller with the path POST /v1/employeedocuments
axios({
method: 'POST',
url: '/v1/employeedocuments',
data: {
employeeProfileId:"ID",
documentType:"String",
documentUrl:"String",
validUntil:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeDocument",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"employeeDocument": {
"id": "ID",
"employeeProfileId": "ID",
"documentType": "String",
"documentUrl": "String",
"validUntil": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Employeedocument API
[Default update API] — This is the designated default update API for the employeeDocument data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Update a specific employee document (e.g., to update expiration date or replace file reference).
Rest Route
The updateEmployeeDocument API REST controller can be triggered via the following route:
/v1/employeedocuments/:employeeDocumentId
Rest Request Parameters
The updateEmployeeDocument api has got 4 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeDocumentId | ID | true | request.params?.[“employeeDocumentId”] |
| documentType | String | false | request.body?.[“documentType”] |
| documentUrl | String | false | request.body?.[“documentUrl”] |
| validUntil | Date | false | request.body?.[“validUntil”] |
| employeeDocumentId : This id paremeter is used to select the required data object that will be updated | |||
| documentType : Type of document (e.g., ID, contract, certification). | |||
| documentUrl : URL to the file storage location or bucket for this document. | |||
| validUntil : Expiration date of document, if applicable. Used for tracking compliance/renewal. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/employeedocuments/:employeeDocumentId
axios({
method: 'PATCH',
url: `/v1/employeedocuments/${employeeDocumentId}`,
data: {
documentType:"String",
documentUrl:"String",
validUntil:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeDocument",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"employeeDocument": {
"id": "ID",
"employeeProfileId": "ID",
"documentType": "String",
"documentUrl": "String",
"validUntil": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Employeedocument API
[Default get API] — This is the designated default get API for the employeeDocument data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get a specific employee document by ID, with enriched employeeProfile info.
Rest Route
The getEmployeeDocument API REST controller can be triggered via the following route:
/v1/employeedocuments/:employeeDocumentId
Rest Request Parameters
The getEmployeeDocument api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeDocumentId | ID | true | request.params?.[“employeeDocumentId”] |
| employeeDocumentId : 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/employeedocuments/:employeeDocumentId
axios({
method: 'GET',
url: `/v1/employeedocuments/${employeeDocumentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeDocument",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"employeeDocument": {
"id": "ID",
"employeeProfileId": "ID",
"documentType": "String",
"documentUrl": "String",
"validUntil": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"employeeProfile": {
"userId": "ID",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer"
}
}
}
List Employeedocuments API
[Default list API] — This is the designated default list API for the employeeDocument data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List all documents for employee profiles (optionally filtered by type, validity, or profile).
Rest Route
The listEmployeeDocuments API REST controller can be triggered via the following route:
/v1/employeedocuments
Rest Request Parameters
Filter Parameters
The listEmployeeDocuments api supports 2 optional filter parameters for filtering list results:
employeeProfileId (ID): Reference to the related employeeProfile record.
- Single:
?employeeProfileId=<value> - Multiple:
?employeeProfileId=<value1>&employeeProfileId=<value2> - Null:
?employeeProfileId=null
validUntil (Date): Expiration date of document, if applicable. Used for tracking compliance/renewal.
- Single date:
?validUntil=2024-01-15 - Multiple dates:
?validUntil=2024-01-15&validUntil=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?validUntil=null
REST Request To access the api you can use the REST controller with the path GET /v1/employeedocuments
axios({
method: 'GET',
url: '/v1/employeedocuments',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// employeeProfileId: '<value>' // Filter by employeeProfileId
// validUntil: '<value>' // Filter by validUntil
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeDocuments",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"employeeDocuments": [
{
"id": "ID",
"employeeProfileId": "ID",
"documentType": "String",
"documentUrl": "String",
"validUntil": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"employeeProfile": {
"userId": "ID",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer"
}
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Delete Employeeprofile API
Rest Route
The deleteEmployeeProfile API REST controller can be triggered via the following route:
/v1/employeeprofiles/:employeeProfileId
Rest Request Parameters
The deleteEmployeeProfile api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeProfileId | ID | true | request.params?.[“employeeProfileId”] |
| employeeProfileId : 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/employeeprofiles/:employeeProfileId
axios({
method: 'DELETE',
url: `/v1/employeeprofiles/${employeeProfileId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeProfile",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"employeeProfile": {
"id": "ID",
"userId": "ID",
"employmentStartDate": "Date",
"position": "String",
"contractType": "Enum",
"contractType_idx": "Integer",
"salary": "Double",
"departmentId": "ID",
"managerId": "ID",
"notes": "Text",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Employeedocument API
Rest Route
The deleteEmployeeDocument API REST controller can be triggered via the following route:
/v1/employeedocuments/:employeeDocumentId
Rest Request Parameters
The deleteEmployeeDocument api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| employeeDocumentId | ID | true | request.params?.[“employeeDocumentId”] |
| employeeDocumentId : 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/employeedocuments/:employeeDocumentId
axios({
method: 'DELETE',
url: `/v1/employeedocuments/${employeeDocumentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "employeeDocument",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"employeeDocument": {
"id": "ID",
"employeeProfileId": "ID",
"documentType": "String",
"documentUrl": "String",
"validUntil": "Date",
"companyId": "ID",
"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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - ScheduleManagement Service
This document is a part of a REST API guide for the workforceos 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 scheduleManagement
Service Access
ScheduleManagement service management is handled through service specific base urls.
ScheduleManagement 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 scheduleManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/schedulemanagement-api - Staging:
https://workforceos-stage.mindbricks.co/schedulemanagement-api - Production:
https://workforceos.mindbricks.co/schedulemanagement-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to scheduleManagement service.
Scope
ScheduleManagement Service Description
Microservice managing shift scheduling, shift templates, assignment of users/departments to shifts, and schedule conflict detection for WorkforceOS.
ScheduleManagement service provides apis and business logic for following data objects in workforceos 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.
shiftTemplate Data Object: Template for recurring or standard shift patterns. Owned by company. Used to quickly schedule repeatable work shifts; optionally scoped to a department.
shift Data Object: A scheduled shift for a company. Defines date, time span, location, and assignment to users/departments. Core entity for workforce operations.
ScheduleManagement Service Frontend Description By The Backend Architect
This service manages all backend logic and data storage for shift schedules, shift templates, and employee assignments. Shifts and templates are accessible for creation and viewing according to user role; only users with admin/manager roles can modify, while regular employees can view only their assigned shifts. Responses for get/list APIs are enriched to provide user and department names for frontend efficiency. Validation error messages should be displayed inline for any scheduling conflicts. Shift times and recurrences should be formatted in user local time via the 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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
ShiftTemplate Data Object
Template for recurring or standard shift patterns. Owned by company. Used to quickly schedule repeatable work shifts; optionally scoped to a department.
ShiftTemplate Data Object Frontend Description By The Backend Architect
Shift templates allow admins/managers to create reusable patterns for common/cyclic shifts. They define default times, recurrence (RFC5545 rule, e.g. weekly), and optionally restrict assignment to a specific department. Used when building the schedule calendar.
ShiftTemplate Data Object Properties
ShiftTemplate data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.
| Property | Type | IsArray | Required | Secret | Description |
|---|---|---|---|---|---|
name |
String | false | Yes | No | Display name for the template (e.g., ‘Morning Shift’). |
description |
Text | false | No | No | Description/purpose of the shift template. |
startTime |
String | false | Yes | No | Template start time in HH:mm format. |
endTime |
String | false | Yes | No | Template end time in HH:mm format. |
recurrenceRule |
String | false | Yes | No | RFC 5545 RRULE-formatted string describing recurrence (e.g., weekly, biweekly). |
departmentId |
ID | false | No | No | Restricts applicability of template to a department if set. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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
departmentId
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.
- departmentId: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
name departmentId companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
name: String has a filter named
name -
departmentId: ID has a filter named
departmentId -
companyId: ID has a filter named
companyId
Shift Data Object
A scheduled shift for a company. Defines date, time span, location, and assignment to users/departments. Core entity for workforce operations.
Shift Data Object Frontend Description By The Backend Architect
A shift marks a scheduled work period. It includes the date, start/end time, location, and which users or departments are assigned. Only admin/manager roles can create/modify shifts. Employees see only shifts assigned to them (directly or via their department). Changes should be reflected in shift lists in near real-time.
Shift Data Object Properties
Shift 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 |
|---|---|---|---|---|---|
shiftDate |
Date | false | Yes | No | Date of shift (YYYY-MM-DD). |
startTime |
String | false | Yes | No | Shift start time (HH:mm local time). |
endTime |
String | false | Yes | No | Shift end time (HH:mm local time). |
location |
String | false | No | No | Physical or logical location for the shift (if applicable). |
departmentId |
ID | false | No | No | Limits or indicates department responsible for this shift. |
assignedUserIds |
ID | true | No | No | User IDs assigned to the shift. |
assignedDepartmentIds |
ID | true | No | No | Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned. |
status |
Enum | false | Yes | No | Status of the shift (scheduled, completed, cancelled). |
createdBy |
ID | false | Yes | No | User who created the shift. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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
assignedUserIds assignedDepartmentIds
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.
- status: [scheduled, completed, cancelled]
Relation Properties
departmentId 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.
- departmentId: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- createdBy: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
shiftDate departmentId assignedUserIds assignedDepartmentIds status companyId
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.
-
shiftDate: Date has a filter named
shiftDate -
departmentId: ID has a filter named
departmentId -
assignedUserIds: ID has a filter named
assignedUserIds -
assignedDepartmentIds: ID has a filter named
assignedDepartmentIds -
status: Enum has a filter named
status -
companyId: ID has a filter named
companyId
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.
ShiftTemplate Default APIs
Display Label Property: name — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createShiftTemplate |
/v1/shifttemplates |
Yes |
| Update | updateShiftTemplate |
/v1/shifttemplates/:shiftTemplateId |
Yes |
| Delete | deleteShiftTemplate |
/v1/shifttemplates/:shiftTemplateId |
Yes |
| Get | getShiftTemplate |
/v1/shifttemplates/:shiftTemplateId |
Yes |
| List | listShiftTemplates |
/v1/shifttemplates |
Yes |
Shift Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createShift |
/v1/shifts |
Yes |
| Update | updateShift |
/v1/shifts/:shiftId |
Yes |
| Delete | deleteShift |
/v1/shifts/:shiftId |
Yes |
| Get | getShift |
/v1/shifts/:shiftId |
Yes |
| List | listShifts |
/v1/shifts |
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 Shifttemplate API
[Default create API] — This is the designated default create API for the shiftTemplate data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Create a new shift template for the company.
Rest Route
The createShiftTemplate API REST controller can be triggered via the following route:
/v1/shifttemplates
Rest Request Parameters
The createShiftTemplate api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| name | String | true | request.body?.[“name”] |
| description | Text | false | request.body?.[“description”] |
| startTime | String | true | request.body?.[“startTime”] |
| endTime | String | true | request.body?.[“endTime”] |
| recurrenceRule | String | true | request.body?.[“recurrenceRule”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| name : Display name for the template (e.g., ‘Morning Shift’). | |||
| description : Description/purpose of the shift template. | |||
| startTime : Template start time in HH:mm format. | |||
| endTime : Template end time in HH:mm format. | |||
| recurrenceRule : RFC 5545 RRULE-formatted string describing recurrence (e.g., weekly, biweekly). | |||
| departmentId : Restricts applicability of template to a department if set. |
REST Request To access the api you can use the REST controller with the path POST /v1/shifttemplates
axios({
method: 'POST',
url: '/v1/shifttemplates',
data: {
name:"String",
description:"Text",
startTime:"String",
endTime:"String",
recurrenceRule:"String",
departmentId:"ID",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shiftTemplate",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"shiftTemplate": {
"id": "ID",
"name": "String",
"description": "Text",
"startTime": "String",
"endTime": "String",
"recurrenceRule": "String",
"departmentId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Shifttemplate API
[Default update API] — This is the designated default update API for the shiftTemplate data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Update an existing shift template.
Rest Route
The updateShiftTemplate API REST controller can be triggered via the following route:
/v1/shifttemplates/:shiftTemplateId
Rest Request Parameters
The updateShiftTemplate api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftTemplateId | ID | true | request.params?.[“shiftTemplateId”] |
| name | String | false | request.body?.[“name”] |
| description | Text | false | request.body?.[“description”] |
| startTime | String | false | request.body?.[“startTime”] |
| endTime | String | false | request.body?.[“endTime”] |
| recurrenceRule | String | false | request.body?.[“recurrenceRule”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| shiftTemplateId : This id paremeter is used to select the required data object that will be updated | |||
| name : Display name for the template (e.g., ‘Morning Shift’). | |||
| description : Description/purpose of the shift template. | |||
| startTime : Template start time in HH:mm format. | |||
| endTime : Template end time in HH:mm format. | |||
| recurrenceRule : RFC 5545 RRULE-formatted string describing recurrence (e.g., weekly, biweekly). | |||
| departmentId : Restricts applicability of template to a department if set. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/shifttemplates/:shiftTemplateId
axios({
method: 'PATCH',
url: `/v1/shifttemplates/${shiftTemplateId}`,
data: {
name:"String",
description:"Text",
startTime:"String",
endTime:"String",
recurrenceRule:"String",
departmentId:"ID",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shiftTemplate",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"shiftTemplate": {
"id": "ID",
"name": "String",
"description": "Text",
"startTime": "String",
"endTime": "String",
"recurrenceRule": "String",
"departmentId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Shifttemplate API
[Default delete API] — This is the designated default delete API for the shiftTemplate data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Delete a shift template by id.
Rest Route
The deleteShiftTemplate API REST controller can be triggered via the following route:
/v1/shifttemplates/:shiftTemplateId
Rest Request Parameters
The deleteShiftTemplate api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftTemplateId | ID | true | request.params?.[“shiftTemplateId”] |
| shiftTemplateId : 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/shifttemplates/:shiftTemplateId
axios({
method: 'DELETE',
url: `/v1/shifttemplates/${shiftTemplateId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shiftTemplate",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"shiftTemplate": {
"id": "ID",
"name": "String",
"description": "Text",
"startTime": "String",
"endTime": "String",
"recurrenceRule": "String",
"departmentId": "ID",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Shifttemplate API
[Default get API] — This is the designated default get API for the shiftTemplate data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get detailed info for a shift template.
Rest Route
The getShiftTemplate API REST controller can be triggered via the following route:
/v1/shifttemplates/:shiftTemplateId
Rest Request Parameters
The getShiftTemplate api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftTemplateId | ID | true | request.params?.[“shiftTemplateId”] |
| shiftTemplateId : 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/shifttemplates/:shiftTemplateId
axios({
method: 'GET',
url: `/v1/shifttemplates/${shiftTemplateId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shiftTemplate",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"shiftTemplate": {
"id": "ID",
"name": "String",
"description": "Text",
"startTime": "String",
"endTime": "String",
"recurrenceRule": "String",
"departmentId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Shifttemplates API
[Default list API] — This is the designated default list API for the shiftTemplate data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List all shift templates for the company, filterable by department.
Rest Route
The listShiftTemplates API REST controller can be triggered via the following route:
/v1/shifttemplates
Rest Request Parameters
Filter Parameters
The listShiftTemplates api supports 2 optional filter parameters for filtering list results:
name (String): Display name for the template (e.g., ‘Morning Shift’).
- Single (partial match, case-insensitive):
?name=<value> - Multiple:
?name=<value1>&name=<value2> - Null:
?name=null
departmentId (ID): Restricts applicability of template to a department if set.
- Single:
?departmentId=<value> - Multiple:
?departmentId=<value1>&departmentId=<value2> - Null:
?departmentId=null
REST Request To access the api you can use the REST controller with the path GET /v1/shifttemplates
axios({
method: 'GET',
url: '/v1/shifttemplates',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// name: '<value>' // Filter by name
// departmentId: '<value>' // Filter by departmentId
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shiftTemplates",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"shiftTemplates": [
{
"id": "ID",
"name": "String",
"description": "Text",
"startTime": "String",
"endTime": "String",
"recurrenceRule": "String",
"departmentId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"department": [
null,
null,
null
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Create Shift API
[Default create API] — This is the designated default create API for the shift data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Create a shift for a specific date, with assigned users or departments. Enforces conflict detection: blocks if any assigned user has an overlapping shift OR an approved leave request covering the shift date.
Rest Route
The createShift API REST controller can be triggered via the following route:
/v1/shifts
Rest Request Parameters
The createShift api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftDate | Date | true | request.body?.[“shiftDate”] |
| startTime | String | true | request.body?.[“startTime”] |
| endTime | String | true | request.body?.[“endTime”] |
| location | String | false | request.body?.[“location”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| assignedUserIds | ID | false | request.body?.[“assignedUserIds”] |
| assignedDepartmentIds | ID | false | request.body?.[“assignedDepartmentIds”] |
| status | Enum | true | request.body?.[“status”] |
| shiftDate : Date of shift (YYYY-MM-DD). | |||
| startTime : Shift start time (HH:mm local time). | |||
| endTime : Shift end time (HH:mm local time). | |||
| location : Physical or logical location for the shift (if applicable). | |||
| departmentId : Limits or indicates department responsible for this shift. | |||
| assignedUserIds : User IDs assigned to the shift. | |||
| assignedDepartmentIds : Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned. | |||
| status : Status of the shift (scheduled, completed, cancelled). |
REST Request To access the api you can use the REST controller with the path POST /v1/shifts
axios({
method: 'POST',
url: '/v1/shifts',
data: {
shiftDate:"Date",
startTime:"String",
endTime:"String",
location:"String",
departmentId:"ID",
assignedUserIds:"ID",
assignedDepartmentIds:"ID",
status:"Enum",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shift",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"shift": {
"id": "ID",
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "ID",
"assignedUserIds": "ID",
"assignedDepartmentIds": "ID",
"status": "Enum",
"status_idx": "Integer",
"createdBy": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Shift API
[Default update API] — This is the designated default update API for the shift data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Update details or assignment of an existing shift. Runs conflict detection on new assignments: blocks if any assigned user has an overlapping shift OR an approved leave request covering the shift date.
Rest Route
The updateShift API REST controller can be triggered via the following route:
/v1/shifts/:shiftId
Rest Request Parameters
The updateShift api has got 9 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftId | ID | true | request.params?.[“shiftId”] |
| shiftDate | Date | true | request.body?.[“shiftDate”] |
| startTime | String | true | request.body?.[“startTime”] |
| endTime | String | true | request.body?.[“endTime”] |
| location | String | false | request.body?.[“location”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| assignedUserIds | ID | false | request.body?.[“assignedUserIds”] |
| assignedDepartmentIds | ID | false | request.body?.[“assignedDepartmentIds”] |
| status | Enum | false | request.body?.[“status”] |
| shiftId : This id paremeter is used to select the required data object that will be updated | |||
| shiftDate : Date of shift (YYYY-MM-DD). | |||
| startTime : Shift start time (HH:mm local time). | |||
| endTime : Shift end time (HH:mm local time). | |||
| location : Physical or logical location for the shift (if applicable). | |||
| departmentId : Limits or indicates department responsible for this shift. | |||
| assignedUserIds : User IDs assigned to the shift. | |||
| assignedDepartmentIds : Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned. | |||
| status : Status of the shift (scheduled, completed, cancelled). |
REST Request To access the api you can use the REST controller with the path PATCH /v1/shifts/:shiftId
axios({
method: 'PATCH',
url: `/v1/shifts/${shiftId}`,
data: {
shiftDate:"Date",
startTime:"String",
endTime:"String",
location:"String",
departmentId:"ID",
assignedUserIds:"ID",
assignedDepartmentIds:"ID",
status:"Enum",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shift",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"shift": {
"id": "ID",
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "ID",
"assignedUserIds": "ID",
"assignedDepartmentIds": "ID",
"status": "Enum",
"status_idx": "Integer",
"createdBy": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Shift API
[Default delete API] — This is the designated default delete API for the shift data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Delete a shift by id.
Rest Route
The deleteShift API REST controller can be triggered via the following route:
/v1/shifts/:shiftId
Rest Request Parameters
The deleteShift api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftId | ID | true | request.params?.[“shiftId”] |
| shiftId : 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/shifts/:shiftId
axios({
method: 'DELETE',
url: `/v1/shifts/${shiftId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shift",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"shift": {
"id": "ID",
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "ID",
"assignedUserIds": "ID",
"assignedDepartmentIds": "ID",
"status": "Enum",
"status_idx": "Integer",
"createdBy": "ID",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Shift API
[Default get API] — This is the designated default get API for the shift data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get details for a specific shift (enriched with user and department info for assignments).
Rest Route
The getShift API REST controller can be triggered via the following route:
/v1/shifts/:shiftId
Rest Request Parameters
The getShift api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftId | ID | true | request.params?.[“shiftId”] |
| shiftId : 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/shifts/:shiftId
axios({
method: 'GET',
url: `/v1/shifts/${shiftId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shift",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"shift": {
"id": "ID",
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "ID",
"assignedUserIds": "ID",
"assignedDepartmentIds": "ID",
"status": "Enum",
"status_idx": "Integer",
"createdBy": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"assignedUsers": {
"fullname": "String",
"avatar": "String"
},
"createdByUser": {
"fullname": "String",
"avatar": "String"
}
}
}
List Shifts API
[Default list API] — This is the designated default list API for the shift data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List all shifts, filterable by date, assigned user, department, status, etc. Employees can see only shifts assigned to them or their department.
Rest Route
The listShifts API REST controller can be triggered via the following route:
/v1/shifts
Rest Request Parameters
Filter Parameters
The listShifts api supports 7 optional filter parameters for filtering list results:
shiftDate (Date): Date of shift (YYYY-MM-DD).
- Single date:
?shiftDate=2024-01-15 - Multiple dates:
?shiftDate=2024-01-15&shiftDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?shiftDate=null
departmentId (ID): Limits or indicates department responsible for this shift.
- Single:
?departmentId=<value> - Multiple:
?departmentId=<value1>&departmentId=<value2> - Null:
?departmentId=null
assignedUserIds (ID array): User IDs assigned to the shift.
- Single:
?assignedUserIds=<value> - Multiple:
?assignedUserIds=<value1>&assignedUserIds=<value2> - Null:
?assignedUserIds=null - Array contains:
?assignedUserIds=<value>&assignedUserIds_op=contains(default) - Array overlap:
?assignedUserIds=<value1>&assignedUserIds=<value2>&assignedUserIds_op=overlap
assignedUserIds_op (String): Operator for filtering array property “assignedUserIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.
- Single (partial match, case-insensitive):
?assignedUserIds_op=<value> - Multiple:
?assignedUserIds_op=<value1>&assignedUserIds_op=<value2> - Null:
?assignedUserIds_op=null
assignedDepartmentIds (ID array): Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned.
- Single:
?assignedDepartmentIds=<value> - Multiple:
?assignedDepartmentIds=<value1>&assignedDepartmentIds=<value2> - Null:
?assignedDepartmentIds=null - Array contains:
?assignedDepartmentIds=<value>&assignedDepartmentIds_op=contains(default) - Array overlap:
?assignedDepartmentIds=<value1>&assignedDepartmentIds=<value2>&assignedDepartmentIds_op=overlap
assignedDepartmentIds_op (String): Operator for filtering array property “assignedDepartmentIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.
- Single (partial match, case-insensitive):
?assignedDepartmentIds_op=<value> - Multiple:
?assignedDepartmentIds_op=<value1>&assignedDepartmentIds_op=<value2> - Null:
?assignedDepartmentIds_op=null
status (Enum): Status of the shift (scheduled, completed, cancelled).
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
REST Request To access the api you can use the REST controller with the path GET /v1/shifts
axios({
method: 'GET',
url: '/v1/shifts',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// shiftDate: '<value>' // Filter by shiftDate
// departmentId: '<value>' // Filter by departmentId
// assignedUserIds: '<value>' // Filter by assignedUserIds
// assignedUserIds_op: '<value>' // Filter by assignedUserIds_op
// assignedDepartmentIds: '<value>' // Filter by assignedDepartmentIds
// assignedDepartmentIds_op: '<value>' // Filter by assignedDepartmentIds_op
// status: '<value>' // Filter by status
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "shifts",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"shifts": [
{
"id": "ID",
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "ID",
"assignedUserIds": "ID",
"assignedDepartmentIds": "ID",
"status": "Enum",
"status_idx": "Integer",
"createdBy": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"assignedUsers": [
{
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"assignedDepartments": [
null,
null,
null
],
"department": [
null,
null,
null
],
"createdByUser": [
{
"fullname": "String",
"avatar": "String"
},
{},
{}
]
},
{},
{}
],
"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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - AttendanceManagement Service
This document is a part of a REST API guide for the workforceos 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 attendanceManagement
Service Access
AttendanceManagement service management is handled through service specific base urls.
AttendanceManagement 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 attendanceManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/attendancemanagement-api - Staging:
https://workforceos-stage.mindbricks.co/attendancemanagement-api - Production:
https://workforceos.mindbricks.co/attendancemanagement-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to attendanceManagement service.
Scope
AttendanceManagement Service Description
Handles employee attendance logging (check-in/out), attendance rules (lateness/absence/early-leave), real-time & historical logs, and publishes notification events. Enforces company data isolation, strict record uniqueness, and one-per-shift attendance rule.
AttendanceManagement service provides apis and business logic for following data objects in workforceos 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.
attendanceRecord Data Object: Records a specific user’s attendance for a shift (check-in/out), with status (present, absent, late, leftEarly, pending), lateness minutes, absence reason, and manager/admin notes. Enforces strict uniqueness (one record per user per shift per day) and company-level data isolation.
AttendanceManagement Service Frontend Description By The Backend Architect
This service provides the core backend for check-in/out operations, attendance history display, late/absent detection, and notification triggers to the notification infrastructure. All APIs are strictly company-scoped and role-based: admins/managers have access to all records, employees only to their own. Date/time displays and filtering should be in the company’s local time (handled by frontend). For employees, self-service: Show check-in/out actions only for active assigned shifts, with clear feedback on status (‘checked in’, ‘late’, ‘absent’ only appears after the shift/day). Manager/admin UI must include tools for reviewing attendance by date/employee/shift with visual cues for late/absent; allow manual absence reason/note edits by authorized roles. Pending (not checked out) states must be highlighted for managers/admins and the user.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
AttendanceRecord Data Object
Records a specific user’s attendance for a shift (check-in/out), with status (present, absent, late, leftEarly, pending), lateness minutes, absence reason, and manager/admin notes. Enforces strict uniqueness (one record per user per shift per day) and company-level data isolation.
AttendanceRecord Data Object Frontend Description By The Backend Architect
Represents a single attendance event with check-in and checkout. Use ‘status’ to show if user was present, absent, late, leftEarly, or pending (not checked out yet). Display absenceReason and managerNote only to admins/managers. Employees cannot edit records other than own check-in/out. Enforced 1 record per user/shift/day.
AttendanceRecord Data Object Properties
AttendanceRecord 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 | Referenced user (employee) |
shiftId |
ID | false | Yes | No | Related shift |
checkInTime |
Date | false | Yes | No | User check-in timestamp (set on check-in) |
checkOutTime |
Date | false | No | No | User check-out timestamp (set on check-out) |
status |
Enum | false | Yes | No | Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out) |
lateByMinutes |
Integer | false | No | No | How many minutes late (if late) |
absenceReason |
String | false | No | No | Reason for absence (manager-provided, e.g., sick, leave) |
managerNote |
Text | false | No | No | Manager/admin note (optional for manual absence management) |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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, present, absent, late, leftEarly]
Relation Properties
userId shiftId
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 sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
- shiftId: ID
Relation to
shift.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
Filter Properties
userId shiftId status companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
userId: ID has a filter named
userId -
shiftId: ID has a filter named
shiftId -
status: Enum has a filter named
status -
companyId: ID has a filter named
companyId
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.
AttendanceRecord Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | checkInAttendance |
/v1/check-in |
Yes |
| Update | checkOutAttendance |
/v1/check-out |
Yes |
| Delete | none | - | Auto |
| Get | getAttendanceRecord |
/v1/attendance-records/:attendanceRecordId |
Yes |
| List | listAttendanceRecords |
/v1/attendance-records |
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
Check Inattendance API
[Default create API] — This is the designated default create API for the attendanceRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Allows a user to check in for an assigned shift. Enforces strict one-record-per-user/shift/day, automatically determines status (present/late). Records check-in timestamp; only permitted if user assigned to shift.
API Frontend Description By The Backend Architect
Rendered as employee’s check-in button for assigned shift. Shows feedback on result (on-time/late/error). Manager/admin may impersonate check-in (override role checks).
Rest Route
The checkInAttendance API REST controller can be triggered via the following route:
/v1/check-in
Rest Request Parameters
The checkInAttendance api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| shiftId | ID | true | request.body?.[“shiftId”] |
| userId | ID | true | request.body?.[“userId”] |
| checkInTime | Date | true | request.body?.[“checkInTime”] |
| checkOutTime | Date | false | request.body?.[“checkOutTime”] |
| status | Enum | true | request.body?.[“status”] |
| lateByMinutes | Integer | false | request.body?.[“lateByMinutes”] |
| absenceReason | String | false | request.body?.[“absenceReason”] |
| managerNote | Text | false | request.body?.[“managerNote”] |
| shiftId : ID of the shift for check-in | |||
| userId : Referenced user (employee) | |||
| checkInTime : User check-in timestamp (set on check-in) | |||
| checkOutTime : User check-out timestamp (set on check-out) | |||
| status : Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out) | |||
| lateByMinutes : How many minutes late (if late) | |||
| absenceReason : Reason for absence (manager-provided, e.g., sick, leave) | |||
| managerNote : Manager/admin note (optional for manual absence management) |
REST Request To access the api you can use the REST controller with the path POST /v1/check-in
axios({
method: 'POST',
url: '/v1/check-in',
data: {
shiftId:"ID",
userId:"ID",
checkInTime:"Date",
checkOutTime:"Date",
status:"Enum",
lateByMinutes:"Integer",
absenceReason:"String",
managerNote:"Text",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "attendanceRecord",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"attendanceRecord": {
"id": "ID",
"userId": "ID",
"shiftId": "ID",
"checkInTime": "Date",
"checkOutTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"lateByMinutes": "Integer",
"absenceReason": "String",
"managerNote": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Check Outattendance API
[Default update API] — This is the designated default update API for the attendanceRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Sets check-out timestamp and updates status (if left early), allowed only if check-in exists but no check-out. User may only check out own attendance.
API Frontend Description By The Backend Architect
Rendered as check-out button for active shift; shows result or error why not possible (e.g., already checked out, not checked in, not assigned).
Rest Route
The checkOutAttendance API REST controller can be triggered via the following route:
/v1/check-out
Rest Request Parameters
The checkOutAttendance api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| attendanceRecordId | ID | true | request.body?.[“attendanceRecordId”] |
| checkOutTime | Date | false | request.body?.[“checkOutTime”] |
| status | Enum | true | request.body?.[“status”] |
| lateByMinutes | Integer | false | request.body?.[“lateByMinutes”] |
| absenceReason | String | false | request.body?.[“absenceReason”] |
| managerNote | Text | false | request.body?.[“managerNote”] |
| attendanceRecordId : ID of the attendance record to check out (must be of current user and not already checked out) | |||
| checkOutTime : User check-out timestamp (set on check-out) | |||
| status : Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out) | |||
| lateByMinutes : How many minutes late (if late) | |||
| absenceReason : Reason for absence (manager-provided, e.g., sick, leave) | |||
| managerNote : Manager/admin note (optional for manual absence management) |
REST Request To access the api you can use the REST controller with the path POST /v1/check-out
axios({
method: 'POST',
url: '/v1/check-out',
data: {
attendanceRecordId:"ID",
checkOutTime:"Date",
status:"Enum",
lateByMinutes:"Integer",
absenceReason:"String",
managerNote:"Text",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "attendanceRecord",
"method": "POST",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"attendanceRecord": {
"id": "ID",
"userId": "ID",
"shiftId": "ID",
"checkInTime": "Date",
"checkOutTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"lateByMinutes": "Integer",
"absenceReason": "String",
"managerNote": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Mark Attendanceabsent API
Manager/admin marks an employee as absent for a shift (typically after missed check-in). Can set absenceReason, and adds admin note.
API Frontend Description By The Backend Architect
For managers/admins: select user/shift, set absence reason/note. No employee self-access.
Rest Route
The markAttendanceAbsent API REST controller can be triggered via the following route:
/v1/mark-absent
Rest Request Parameters
The markAttendanceAbsent api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| userId | ID | true | request.body?.[“userId”] |
| shiftId | ID | true | request.body?.[“shiftId”] |
| absenceReason | String | false | request.body?.[“absenceReason”] |
| managerNote | Text | false | request.body?.[“managerNote”] |
| checkOutTime | Date | false | request.body?.[“checkOutTime”] |
| status | Enum | true | request.body?.[“status”] |
| lateByMinutes | Integer | false | request.body?.[“lateByMinutes”] |
| userId : User to be marked absent | |||
| shiftId : Shift for absence | |||
| absenceReason : Reason for absence | |||
| managerNote : Manager note (internal) | |||
| checkOutTime : User check-out timestamp (set on check-out) | |||
| status : Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out) | |||
| lateByMinutes : How many minutes late (if late) |
REST Request To access the api you can use the REST controller with the path POST /v1/mark-absent
axios({
method: 'POST',
url: '/v1/mark-absent',
data: {
userId:"ID",
shiftId:"ID",
absenceReason:"String",
managerNote:"Text",
checkOutTime:"Date",
status:"Enum",
lateByMinutes:"Integer",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "attendanceRecord",
"method": "POST",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"attendanceRecord": {
"id": "ID",
"userId": "ID",
"shiftId": "ID",
"checkInTime": "Date",
"checkOutTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"lateByMinutes": "Integer",
"absenceReason": "String",
"managerNote": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Attendancerecord API
[Default get API] — This is the designated default get API for the attendanceRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get an attendance record by ID; enrichment with user/shift details. Employees can see only their own; admin/manager can view any in company.
API Frontend Description By The Backend Architect
For employees: show own record only; enriched with shift info. For admins/managers: enriched with user/shift and notes fields.
Rest Route
The getAttendanceRecord API REST controller can be triggered via the following route:
/v1/attendance-records/:attendanceRecordId
Rest Request Parameters
The getAttendanceRecord api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| attendanceRecordId | ID | true | request.params?.[“attendanceRecordId”] |
| attendanceRecordId : Attendance record ID |
REST Request To access the api you can use the REST controller with the path GET /v1/attendance-records/:attendanceRecordId
axios({
method: 'GET',
url: `/v1/attendance-records/${attendanceRecordId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "attendanceRecord",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"attendanceRecord": {
"id": "ID",
"userId": "ID",
"shiftId": "ID",
"checkInTime": "Date",
"checkOutTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"lateByMinutes": "Integer",
"absenceReason": "String",
"managerNote": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": {
"email": "String",
"fullname": "String",
"avatar": "String"
},
"shift": {
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "ID"
}
}
}
List Attendancerecords API
[Default list API] — This is the designated default list API for the attendanceRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Lists attendance records, filterable by user, shift, status, date. Employees see only own, admin/manager all for company. Enriches with user & shift info.
API Frontend Description By The Backend Architect
Paged list for quick view of attendance, filter/search by user, shift, status, date. Show basic status; enrich row with user & shift as appropriate. Employee may only see own.
Rest Route
The listAttendanceRecords API REST controller can be triggered via the following route:
/v1/attendance-records
Rest Request Parameters
Filter Parameters
The listAttendanceRecords api supports 3 optional filter parameters for filtering list results:
userId (ID): Referenced user (employee)
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
shiftId (ID): Related shift
- Single:
?shiftId=<value> - Multiple:
?shiftId=<value1>&shiftId=<value2> - Null:
?shiftId=null
status (Enum): Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out)
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
REST Request To access the api you can use the REST controller with the path GET /v1/attendance-records
axios({
method: 'GET',
url: '/v1/attendance-records',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '<value>' // Filter by userId
// shiftId: '<value>' // Filter by shiftId
// status: '<value>' // Filter by status
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "attendanceRecords",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"attendanceRecords": [
{
"id": "ID",
"userId": "ID",
"shiftId": "ID",
"checkInTime": "Date",
"checkOutTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"lateByMinutes": "Integer",
"absenceReason": "String",
"managerNote": "Text",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"shift": [
{
"shiftDate": "Date",
"startTime": "String",
"endTime": "String",
"location": "String",
"departmentId": "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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - TaskManagement Service
This document is a part of a REST API guide for the workforceos 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 taskManagement
Service Access
TaskManagement service management is handled through service specific base urls.
TaskManagement 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 taskManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/taskmanagement-api - Staging:
https://workforceos-stage.mindbricks.co/taskmanagement-api - Production:
https://workforceos.mindbricks.co/taskmanagement-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to taskManagement service.
Scope
TaskManagement Service Description
Handles creation, assignment, update, and tracking of tasks tied to employees, shifts, or departments. Supports admins/managers assigning tasks; employees viewing and completing tasks; accountability tracking. Exposes APIs for creating, updating, deleting, and listing tasks with data enrichment. Data is .company-tenant-scoped…
TaskManagement service provides apis and business logic for following data objects in workforceos 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.
taskAssignment Data Object: Main task assignment created by admins/managers. Defines the task template and target recipients (users/departments). Individual tasks are auto-generated for each employee from this assignment.
individualTask Data Object: Individual task record assigned to a single employee. Created automatically when a taskAssignment is created. Each employee works on their own copy and can mark it complete independently.
TaskManagement Service Frontend Description By The Backend Architect
taskManagement Service Communication
- Employee home and shift/department views should display all incomplete or relevant completed tasks assigned to the user (directly), their departments, or their upcoming/active shifts (using listTasks).
- Marking a task as completed/completing should be a one-click or action-card operation; the API returns updated status and completion info.
- Admins/managers see all tasks for their company; filters for department/shift/assignee are available in all listing views.
- Tasks may be created for an individual (assigneeUserIds), group (departmentId), or shift (shiftId), or any combination (multi-context assignment).
- Responsibility completion and history views rely on enriched getTask/listTasks endpoints (which join assigner/assignee/shift/department/completion info).
- Alerts and notification triggers are not handled here; the frontend should listen for API events and/or subscribe to notification topics via notificationService frontend modules.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
TaskAssignment Data Object
Main task assignment created by admins/managers. Defines the task template and target recipients (users/departments). Individual tasks are auto-generated for each employee from this assignment.
TaskAssignment Data Object Properties
TaskAssignment 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 | Task title visible to all assignees |
description |
Text | false | No | No | Detailed task description |
dueTime |
Date | false | No | No | Deadline for task completion |
status |
Enum | false | Yes | No | Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment) |
assignerId |
ID | false | Yes | No | User who created this task assignment |
assigneeUserIds |
ID | true | No | No | Direct user assignments - these users will receive individual tasks |
assignedDepartmentIds |
ID | true | No | No | Department assignments - all users in these departments will receive individual tasks |
shiftId |
ID | false | No | No | Optional shift link for the task |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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
assigneeUserIds assignedDepartmentIds
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.
- status: [active, cancelled, completed]
Relation Properties
assignerId assigneeUserIds assignedDepartmentIds shiftId
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.
- assignerId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
- assigneeUserIds: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- assignedDepartmentIds: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- shiftId: ID
Relation to
shift.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
title dueTime status assignerId assigneeUserIds assignedDepartmentIds shiftId companyId
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 -
dueTime: Date has a filter named
dueTime -
status: Enum has a filter named
status -
assignerId: ID has a filter named
assignerId -
assigneeUserIds: ID has a filter named
assigneeUserIds -
assignedDepartmentIds: ID has a filter named
assignedDepartmentIds -
shiftId: ID has a filter named
shiftId -
companyId: ID has a filter named
companyId
IndividualTask Data Object
Individual task record assigned to a single employee. Created automatically when a taskAssignment is created. Each employee works on their own copy and can mark it complete independently.
IndividualTask Data Object Properties
IndividualTask 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 |
|---|---|---|---|---|---|
taskAssignmentId |
ID | false | Yes | No | Reference to the parent task assignment |
assigneeUserId |
ID | false | Yes | No | The employee who receives this individual task |
title |
String | false | Yes | No | Task title (copied from parent assignment) |
description |
Text | false | No | No | Task description (copied from parent assignment) |
status |
Enum | false | Yes | No | Individual task status: pending, completed, or cancelled |
completedTime |
Date | false | No | No | When this employee completed their task |
dueTime |
Date | false | No | No | Deadline for completion (copied from parent) |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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, completed, cancelled]
Relation Properties
assigneeUserId
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.
- assigneeUserId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
Filter Properties
taskAssignmentId assigneeUserId status dueTime companyId
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.
-
taskAssignmentId: ID has a filter named
taskAssignmentId -
assigneeUserId: ID has a filter named
assigneeUserId -
status: Enum has a filter named
status -
dueTime: Date has a filter named
dueTime -
companyId: ID has a filter named
companyId
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.
TaskAssignment Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createTaskAssignment |
/v1/taskassignments |
Auto |
| Update | updateTaskAssignment |
/v1/taskassignments/:taskAssignmentId |
Auto |
| Delete | deleteTaskAssignment |
/v1/taskassignments/:taskAssignmentId |
Auto |
| Get | getTaskAssignmentWithProgress |
/v1/taskassignmentwithprogress/:taskAssignmentId |
Auto |
| List | listTaskAssignments |
/v1/taskassignments |
Auto |
IndividualTask Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createIndividualTask |
/v1/individualtasks |
Auto |
| Update | updateIndividualTask |
/v1/individualtasks/:individualTaskId |
Auto |
| Delete | deleteIndividualTask |
/v1/individualtasks/:individualTaskId |
Auto |
| Get | getMyIndividualTask |
/v1/myindividualtask/:individualTaskId |
Auto |
| List | listMyIndividualTasks |
/v1/myindividualtasks |
Auto |
When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.
API Reference
Create Taskassignment API
Admin/Manager creates a task assignment. System automatically creates individual task records for all assigned users (direct + from departments) with deduplication.
Rest Route
The createTaskAssignment API REST controller can be triggered via the following route:
/v1/taskassignments
Rest Request Parameters
The createTaskAssignment api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| title | String | true | request.body?.[“title”] |
| description | Text | false | request.body?.[“description”] |
| dueTime | Date | false | request.body?.[“dueTime”] |
| status | Enum | true | request.body?.[“status”] |
| assigneeUserIds | ID | false | request.body?.[“assigneeUserIds”] |
| assignedDepartmentIds | ID | false | request.body?.[“assignedDepartmentIds”] |
| shiftId | ID | false | request.body?.[“shiftId”] |
| title : Task title visible to all assignees | |||
| description : Detailed task description | |||
| dueTime : Deadline for task completion | |||
| status : Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment) | |||
| assigneeUserIds : Direct user assignments - these users will receive individual tasks | |||
| assignedDepartmentIds : Department assignments - all users in these departments will receive individual tasks | |||
| shiftId : Optional shift link for the task |
REST Request To access the api you can use the REST controller with the path POST /v1/taskassignments
axios({
method: 'POST',
url: '/v1/taskassignments',
data: {
title:"String",
description:"Text",
dueTime:"Date",
status:"Enum",
assigneeUserIds:"ID",
assignedDepartmentIds:"ID",
shiftId:"ID",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "taskAssignment",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"taskAssignment": {
"id": "ID",
"title": "String",
"description": "Text",
"dueTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"assignerId": "ID",
"assigneeUserIds": "ID",
"assignedDepartmentIds": "ID",
"shiftId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Myindividualtasks API
Employee lists their own individual tasks. Returns tasks assigned to the current user with optional filtering by status.
Rest Route
The listMyIndividualTasks API REST controller can be triggered via the following route:
/v1/myindividualtasks
Rest Request Parameters
Filter Parameters
The listMyIndividualTasks api supports 4 optional filter parameters for filtering list results:
taskAssignmentId (ID): Reference to the parent task assignment
- Single:
?taskAssignmentId=<value> - Multiple:
?taskAssignmentId=<value1>&taskAssignmentId=<value2> - Null:
?taskAssignmentId=null
assigneeUserId (ID): The employee who receives this individual task
- Single:
?assigneeUserId=<value> - Multiple:
?assigneeUserId=<value1>&assigneeUserId=<value2> - Null:
?assigneeUserId=null
status (Enum): Individual task status: pending, completed, or cancelled
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
dueTime (Date): Deadline for completion (copied from parent)
- Single date:
?dueTime=2024-01-15 - Multiple dates:
?dueTime=2024-01-15&dueTime=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?dueTime=null
REST Request To access the api you can use the REST controller with the path GET /v1/myindividualtasks
axios({
method: 'GET',
url: '/v1/myindividualtasks',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// taskAssignmentId: '<value>' // Filter by taskAssignmentId
// assigneeUserId: '<value>' // Filter by assigneeUserId
// status: '<value>' // Filter by status
// dueTime: '<value>' // Filter by dueTime
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "individualTasks",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"individualTasks": [
{
"id": "ID",
"taskAssignmentId": "ID",
"assigneeUserId": "ID",
"title": "String",
"description": "Text",
"status": "Enum",
"status_idx": "Integer",
"completedTime": "Date",
"dueTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"taskAssignment": {
"title": "String",
"description": "Text",
"dueTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"assignerId": "ID",
"assigneeUserIds": "ID",
"assignedDepartmentIds": "ID",
"shiftId": "ID",
"isActive": true,
"createdAt": "Date",
"updatedAt": "Date"
}
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Get Taskassignmentwithprogress API
Admin/Manager views a task assignment with completion progress. Returns the assignment details along with aggregated stats and list of individual tasks with their completion status.
Rest Route
The getTaskAssignmentWithProgress API REST controller can be triggered via the following route:
/v1/taskassignmentwithprogress/:taskAssignmentId
Rest Request Parameters
The getTaskAssignmentWithProgress api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| taskAssignmentId | ID | true | request.params?.[“taskAssignmentId”] |
| taskAssignmentId : 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/taskassignmentwithprogress/:taskAssignmentId
axios({
method: 'GET',
url: `/v1/taskassignmentwithprogress/${taskAssignmentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "taskAssignment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"taskAssignment": {
"id": "ID",
"title": "String",
"description": "Text",
"dueTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"assignerId": "ID",
"assigneeUserIds": "ID",
"assignedDepartmentIds": "ID",
"shiftId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Myindividualtask API
Employee views a single individual task. Only returns the task if it belongs to the current user.
Rest Route
The getMyIndividualTask API REST controller can be triggered via the following route:
/v1/myindividualtask/:individualTaskId
Rest Request Parameters
The getMyIndividualTask api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| individualTaskId | ID | true | request.params?.[“individualTaskId”] |
| individualTaskId : 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/myindividualtask/:individualTaskId
axios({
method: 'GET',
url: `/v1/myindividualtask/${individualTaskId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "individualTask",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"individualTask": {
"id": "ID",
"taskAssignmentId": "ID",
"assigneeUserId": "ID",
"title": "String",
"description": "Text",
"status": "Enum",
"status_idx": "Integer",
"completedTime": "Date",
"dueTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Taskassignments API
Admin/Manager lists all task assignments in the company. Supports filtering by status, assigner, and due date.
Rest Route
The listTaskAssignments API REST controller can be triggered via the following route:
/v1/taskassignments
Rest Request Parameters
Filter Parameters
The listTaskAssignments api supports 9 optional filter parameters for filtering list results:
title (String): Task title visible to all assignees
- Single (partial match, case-insensitive):
?title=<value> - Multiple:
?title=<value1>&title=<value2> - Null:
?title=null
dueTime (Date): Deadline for task completion
- Single date:
?dueTime=2024-01-15 - Multiple dates:
?dueTime=2024-01-15&dueTime=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?dueTime=null
status (Enum): Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment)
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
assignerId (ID): User who created this task assignment
- Single:
?assignerId=<value> - Multiple:
?assignerId=<value1>&assignerId=<value2> - Null:
?assignerId=null
assigneeUserIds (ID array): Direct user assignments - these users will receive individual tasks
- Single:
?assigneeUserIds=<value> - Multiple:
?assigneeUserIds=<value1>&assigneeUserIds=<value2> - Null:
?assigneeUserIds=null - Array contains:
?assigneeUserIds=<value>&assigneeUserIds_op=contains(default) - Array overlap:
?assigneeUserIds=<value1>&assigneeUserIds=<value2>&assigneeUserIds_op=overlap
assigneeUserIds_op (String): Operator for filtering array property “assigneeUserIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.
- Single (partial match, case-insensitive):
?assigneeUserIds_op=<value> - Multiple:
?assigneeUserIds_op=<value1>&assigneeUserIds_op=<value2> - Null:
?assigneeUserIds_op=null
assignedDepartmentIds (ID array): Department assignments - all users in these departments will receive individual tasks
- Single:
?assignedDepartmentIds=<value> - Multiple:
?assignedDepartmentIds=<value1>&assignedDepartmentIds=<value2> - Null:
?assignedDepartmentIds=null - Array contains:
?assignedDepartmentIds=<value>&assignedDepartmentIds_op=contains(default) - Array overlap:
?assignedDepartmentIds=<value1>&assignedDepartmentIds=<value2>&assignedDepartmentIds_op=overlap
assignedDepartmentIds_op (String): Operator for filtering array property “assignedDepartmentIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.
- Single (partial match, case-insensitive):
?assignedDepartmentIds_op=<value> - Multiple:
?assignedDepartmentIds_op=<value1>&assignedDepartmentIds_op=<value2> - Null:
?assignedDepartmentIds_op=null
shiftId (ID): Optional shift link for the task
- Single:
?shiftId=<value> - Multiple:
?shiftId=<value1>&shiftId=<value2> - Null:
?shiftId=null
REST Request To access the api you can use the REST controller with the path GET /v1/taskassignments
axios({
method: 'GET',
url: '/v1/taskassignments',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// title: '<value>' // Filter by title
// dueTime: '<value>' // Filter by dueTime
// status: '<value>' // Filter by status
// assignerId: '<value>' // Filter by assignerId
// assigneeUserIds: '<value>' // Filter by assigneeUserIds
// assigneeUserIds_op: '<value>' // Filter by assigneeUserIds_op
// assignedDepartmentIds: '<value>' // Filter by assignedDepartmentIds
// assignedDepartmentIds_op: '<value>' // Filter by assignedDepartmentIds_op
// shiftId: '<value>' // Filter by shiftId
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "taskAssignments",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"taskAssignments": [
{
"id": "ID",
"title": "String",
"description": "Text",
"dueTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"assignerId": "ID",
"assigneeUserIds": "ID",
"assignedDepartmentIds": "ID",
"shiftId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Delete Taskassignment API
Rest Route
The deleteTaskAssignment API REST controller can be triggered via the following route:
/v1/taskassignments/:taskAssignmentId
Rest Request Parameters
The deleteTaskAssignment api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| taskAssignmentId | ID | true | request.params?.[“taskAssignmentId”] |
| taskAssignmentId : 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/taskassignments/:taskAssignmentId
axios({
method: 'DELETE',
url: `/v1/taskassignments/${taskAssignmentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "taskAssignment",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"taskAssignment": {
"id": "ID",
"title": "String",
"description": "Text",
"dueTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"assignerId": "ID",
"assigneeUserIds": "ID",
"assignedDepartmentIds": "ID",
"shiftId": "ID",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Individualtask API
Rest Route
The updateIndividualTask API REST controller can be triggered via the following route:
/v1/individualtasks/:individualTaskId
Rest Request Parameters
The updateIndividualTask api has got 5 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| individualTaskId | ID | true | request.params?.[“individualTaskId”] |
| title | String | false | request.body?.[“title”] |
| description | Text | false | request.body?.[“description”] |
| status | Enum | false | request.body?.[“status”] |
| dueTime | Date | false | request.body?.[“dueTime”] |
| individualTaskId : This id paremeter is used to select the required data object that will be updated | |||
| title : Task title (copied from parent assignment) | |||
| description : Task description (copied from parent assignment) | |||
| status : Individual task status: pending, completed, or cancelled | |||
| dueTime : Deadline for completion (copied from parent) |
REST Request To access the api you can use the REST controller with the path PATCH /v1/individualtasks/:individualTaskId
axios({
method: 'PATCH',
url: `/v1/individualtasks/${individualTaskId}`,
data: {
title:"String",
description:"Text",
status:"Enum",
dueTime:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "individualTask",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"individualTask": {
"id": "ID",
"taskAssignmentId": "ID",
"assigneeUserId": "ID",
"title": "String",
"description": "Text",
"status": "Enum",
"status_idx": "Integer",
"completedTime": "Date",
"dueTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Taskassignment API
Rest Route
The updateTaskAssignment API REST controller can be triggered via the following route:
/v1/taskassignments/:taskAssignmentId
Rest Request Parameters
The updateTaskAssignment api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| taskAssignmentId | ID | true | request.params?.[“taskAssignmentId”] |
| title | String | false | request.body?.[“title”] |
| description | Text | false | request.body?.[“description”] |
| dueTime | Date | false | request.body?.[“dueTime”] |
| status | Enum | false | request.body?.[“status”] |
| assigneeUserIds | ID | false | request.body?.[“assigneeUserIds”] |
| assignedDepartmentIds | ID | false | request.body?.[“assignedDepartmentIds”] |
| shiftId | ID | false | request.body?.[“shiftId”] |
| taskAssignmentId : This id paremeter is used to select the required data object that will be updated | |||
| title : Task title visible to all assignees | |||
| description : Detailed task description | |||
| dueTime : Deadline for task completion | |||
| status : Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment) | |||
| assigneeUserIds : Direct user assignments - these users will receive individual tasks | |||
| assignedDepartmentIds : Department assignments - all users in these departments will receive individual tasks | |||
| shiftId : Optional shift link for the task |
REST Request To access the api you can use the REST controller with the path PATCH /v1/taskassignments/:taskAssignmentId
axios({
method: 'PATCH',
url: `/v1/taskassignments/${taskAssignmentId}`,
data: {
title:"String",
description:"Text",
dueTime:"Date",
status:"Enum",
assigneeUserIds:"ID",
assignedDepartmentIds:"ID",
shiftId:"ID",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "taskAssignment",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"taskAssignment": {
"id": "ID",
"title": "String",
"description": "Text",
"dueTime": "Date",
"status": "Enum",
"status_idx": "Integer",
"assignerId": "ID",
"assigneeUserIds": "ID",
"assignedDepartmentIds": "ID",
"shiftId": "ID",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Create Individualtask API
Rest Route
The createIndividualTask API REST controller can be triggered via the following route:
/v1/individualtasks
Rest Request Parameters
The createIndividualTask api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| taskAssignmentId | ID | true | request.body?.[“taskAssignmentId”] |
| assigneeUserId | ID | true | request.body?.[“assigneeUserId”] |
| title | String | true | request.body?.[“title”] |
| description | Text | false | request.body?.[“description”] |
| status | Enum | true | request.body?.[“status”] |
| completedTime | Date | false | request.body?.[“completedTime”] |
| dueTime | Date | false | request.body?.[“dueTime”] |
| taskAssignmentId : Reference to the parent task assignment | |||
| assigneeUserId : The employee who receives this individual task | |||
| title : Task title (copied from parent assignment) | |||
| description : Task description (copied from parent assignment) | |||
| status : Individual task status: pending, completed, or cancelled | |||
| completedTime : When this employee completed their task | |||
| dueTime : Deadline for completion (copied from parent) |
REST Request To access the api you can use the REST controller with the path POST /v1/individualtasks
axios({
method: 'POST',
url: '/v1/individualtasks',
data: {
taskAssignmentId:"ID",
assigneeUserId:"ID",
title:"String",
description:"Text",
status:"Enum",
completedTime:"Date",
dueTime:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "individualTask",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"individualTask": {
"id": "ID",
"taskAssignmentId": "ID",
"assigneeUserId": "ID",
"title": "String",
"description": "Text",
"status": "Enum",
"status_idx": "Integer",
"completedTime": "Date",
"dueTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Individualtask API
Rest Route
The deleteIndividualTask API REST controller can be triggered via the following route:
/v1/individualtasks/:individualTaskId
Rest Request Parameters
The deleteIndividualTask api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| individualTaskId | ID | true | request.params?.[“individualTaskId”] |
| individualTaskId : 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/individualtasks/:individualTaskId
axios({
method: 'DELETE',
url: `/v1/individualtasks/${individualTaskId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "individualTask",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"individualTask": {
"id": "ID",
"taskAssignmentId": "ID",
"assigneeUserId": "ID",
"title": "String",
"description": "Text",
"status": "Enum",
"status_idx": "Integer",
"completedTime": "Date",
"dueTime": "Date",
"companyId": "ID",
"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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - LeaveManagement Service
This document is a part of a REST API guide for the workforceos 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 leaveManagement
Service Access
LeaveManagement service management is handled through service specific base urls.
LeaveManagement 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 leaveManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/leavemanagement-api - Staging:
https://workforceos-stage.mindbricks.co/leavemanagement-api - Production:
https://workforceos.mindbricks.co/leavemanagement-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to leaveManagement service.
Scope
LeaveManagement Service Description
Handles employee leave/absence requests, review/approval workflows, and automatic integration with shift assignments, ensuring company data isolation and leave history access for employees and managers/admins.
LeaveManagement service provides apis and business logic for following data objects in workforceos 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.
leaveRequest Data Object: Tracks employee leave/absence requests including period, type, status, reason, and approval state. Linked to a user and (optionally) department, with audit fields for request and approval. Company-tenant scoped.
LeaveManagement Service Frontend Description By The Backend Architect
UX Hints - leaveManagement Service
- Employees can submit leave requests with start/end dates, reason, and type; can view their own leave history and status.
- Managers/admins see pending leave requests for review, and can approve/reject/cancel with audit trace (approver, decision, date, reason).
- Approval of leave may unassign user from overlapping shifts automatically (notified on shift update).
- Leave requests cannot be edited by employee after review begins (status != pending).
- Employees get notifications upon decision; managers/admins see team/company-wide leave history.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
LeaveRequest Data Object
Tracks employee leave/absence requests including period, type, status, reason, and approval state. Linked to a user and (optionally) department, with audit fields for request and approval. Company-tenant scoped.
LeaveRequest Data Object Frontend Description By The Backend Architect
- Employees submit leave requests for specific periods and types (vacation/sick/etc.).
- Request status/pending until reviewed by an authorized manager/admin.
- Approval auto-triggers removal from conflicting shifts and triggers notifications.
- History and current status visible to both employee and department/company managers/admins.
LeaveRequest Data Object Properties
LeaveRequest 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 | ID of employee/user requesting leave (auth:user.id) |
departmentId |
ID | false | No | No | Department (userGroup) id, for scoping leave if relevant |
requestDate |
Date | false | Yes | No | Datetime when leave requested |
leaveType |
String | false | Yes | No | Type of leave (e.g. vacation, sick, emergency). |
startDate |
Date | false | Yes | No | First day of leave (inclusive). |
endDate |
Date | false | Yes | No | Last day of leave (inclusive). |
reason |
String | false | No | No | Employee-provided reason/message for leave request |
status |
Enum | false | Yes | No | Leave request status (pending, approved, rejected, cancelled). |
approverId |
ID | false | No | No | UserId of manager/admin who approved/rejected/cancelled the request |
approvedDate |
Date | false | No | No | Date/time leave was approved/rejected/cancelled, if applicable. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set.
Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.
- status: [pending, approved, rejected, cancelled]
Relation Properties
userId departmentId approverId
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 sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
- departmentId: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- approverId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
userId departmentId leaveType startDate endDate status companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
userId: ID has a filter named
userId -
departmentId: ID has a filter named
departmentId -
leaveType: String has a filter named
leaveType -
startDate: Date has a filter named
startDate -
endDate: Date has a filter named
endDate -
status: Enum has a filter named
status -
companyId: ID has a filter named
companyId
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.
LeaveRequest Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createLeaveRequest |
/v1/leaverequests |
Yes |
| Update | updateLeaveRequest |
/v1/leaverequests/:leaveRequestId |
Yes |
| Delete | deleteLeaveRequest |
/v1/leaverequests/:leaveRequestId |
Yes |
| Get | getLeaveRequest |
/v1/leaverequests/:leaveRequestId |
Yes |
| List | listLeaveRequests |
/v1/leaverequests |
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 Leaverequest API
[Default create API] — This is the designated default create API for the leaveRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Create a new leave/absence request as an employee user. Sets status to pending. Only allowed if user is creating for themselves. Start and end date are both inclusive.
API Frontend Description By The Backend Architect
- UX: Employee fills leave request form (type, date range, reason). Submission creates pending request. Cannot be submitted for past dates, or overlapping with another approved request. User receives feedback/confirmation; entry appears in leave history.
Rest Route
The createLeaveRequest API REST controller can be triggered via the following route:
/v1/leaverequests
Rest Request Parameters
The createLeaveRequest api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| departmentId | ID | false | request.body?.[“departmentId”] |
| leaveType | String | true | request.body?.[“leaveType”] |
| startDate | Date | true | request.body?.[“startDate”] |
| endDate | Date | true | request.body?.[“endDate”] |
| reason | String | false | request.body?.[“reason”] |
| approverId | ID | false | request.body?.[“approverId”] |
| approvedDate | Date | false | request.body?.[“approvedDate”] |
| departmentId : Department (userGroup) id, for scoping leave if relevant | |||
| leaveType : Type of leave (e.g. vacation, sick, emergency). | |||
| startDate : First day of leave (inclusive). | |||
| endDate : Last day of leave (inclusive). | |||
| reason : Employee-provided reason/message for leave request | |||
| approverId : UserId of manager/admin who approved/rejected/cancelled the request | |||
| approvedDate : Date/time leave was approved/rejected/cancelled, if applicable. |
REST Request To access the api you can use the REST controller with the path POST /v1/leaverequests
axios({
method: 'POST',
url: '/v1/leaverequests',
data: {
departmentId:"ID",
leaveType:"String",
startDate:"Date",
endDate:"Date",
reason:"String",
approverId:"ID",
approvedDate:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequest",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"leaveRequest": {
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Leaverequest API
[Default update API] — This is the designated default update API for the leaveRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Update an existing leave request. Employee can only edit their own request if status is pending. Manager/admin may change status (approve/reject/cancel), set approver/approval date. On approval, will trigger automatic removal from overlapping shifts via scheduleManagement service.
API Frontend Description By The Backend Architect
- UX: Employees can only edit/cancel pending requests. Managers/Admins see status change controls for review (approve/reject/cancel), must provide response (automatically audits approver, time). On approval, user is removed from overlapping shifts and notified.
Rest Route
The updateLeaveRequest API REST controller can be triggered via the following route:
/v1/leaverequests/:leaveRequestId
Rest Request Parameters
The updateLeaveRequest api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| leaveRequestId | ID | true | request.params?.[“leaveRequestId”] |
| departmentId | ID | false | request.body?.[“departmentId”] |
| leaveType | String | false | request.body?.[“leaveType”] |
| startDate | Date | false | request.body?.[“startDate”] |
| endDate | Date | false | request.body?.[“endDate”] |
| reason | String | false | request.body?.[“reason”] |
| approverId | ID | false | request.body?.[“approverId”] |
| approvedDate | Date | false | request.body?.[“approvedDate”] |
| leaveRequestId : This id paremeter is used to select the required data object that will be updated | |||
| departmentId : Department (userGroup) id, for scoping leave if relevant | |||
| leaveType : Type of leave (e.g. vacation, sick, emergency). | |||
| startDate : First day of leave (inclusive). | |||
| endDate : Last day of leave (inclusive). | |||
| reason : Employee-provided reason/message for leave request | |||
| approverId : UserId of manager/admin who approved/rejected/cancelled the request | |||
| approvedDate : Date/time leave was approved/rejected/cancelled, if applicable. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/leaverequests/:leaveRequestId
axios({
method: 'PATCH',
url: `/v1/leaverequests/${leaveRequestId}`,
data: {
departmentId:"ID",
leaveType:"String",
startDate:"Date",
endDate:"Date",
reason:"String",
approverId:"ID",
approvedDate:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequest",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"leaveRequest": {
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Leaverequest API
[Default delete API] — This is the designated default delete API for the leaveRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Delete (soft) a leave request. Only the owner (employee) can delete a pending request; manager/admin may delete any cancelable request. Deletion is soft for audit/history.
API Frontend Description By The Backend Architect
- UX: Employees can delete their own pending requests before review. Admin/manager can delete any not yet actioned or as override. Deletion removes from request history listing (soft deletes only).
Rest Route
The deleteLeaveRequest API REST controller can be triggered via the following route:
/v1/leaverequests/:leaveRequestId
Rest Request Parameters
The deleteLeaveRequest api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| leaveRequestId | ID | true | request.params?.[“leaveRequestId”] |
| leaveRequestId : 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/leaverequests/:leaveRequestId
axios({
method: 'DELETE',
url: `/v1/leaverequests/${leaveRequestId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequest",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"leaveRequest": {
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Leaverequest API
[Default get API] — This is the designated default get API for the leaveRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Retrieve the details of a single leave request record. Enriches with user and department data in response. Owner (employee) can always view own request; admin/manager can view all requests in their company.
API Frontend Description By The Backend Architect
- UX: Employee can view own leave request with details and status. Manager/admin see details and audit info. Related user, department, and approver info shown (join).
Rest Route
The getLeaveRequest API REST controller can be triggered via the following route:
/v1/leaverequests/:leaveRequestId
Rest Request Parameters
The getLeaveRequest api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| leaveRequestId | ID | true | request.params?.[“leaveRequestId”] |
| leaveRequestId : 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/leaverequests/:leaveRequestId
axios({
method: 'GET',
url: `/v1/leaverequests/${leaveRequestId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequest",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"leaveRequest": {
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": {
"email": "String",
"fullname": "String",
"avatar": "String"
},
"approver": {
"email": "String",
"fullname": "String",
"avatar": "String"
}
}
}
List Leaverequests API
[Default list API] — This is the designated default list API for the leaveRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List leave requests visible to the user. Employees see their own; managers/admins can filter by department, user, status, and date. Response includes enrichment joins for user, department, and approver.
API Frontend Description By The Backend Architect
- UX: Employees see their own requests; managers/admins can search/filter requests for department, user, date, or status; list includes enrichment data for related fields.
Rest Route
The listLeaveRequests API REST controller can be triggered via the following route:
/v1/leaverequests
Rest Request Parameters
Filter Parameters
The listLeaveRequests api supports 6 optional filter parameters for filtering list results:
userId (ID): ID of employee/user requesting leave (auth:user.id)
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
departmentId (ID): Department (userGroup) id, for scoping leave if relevant
- Single:
?departmentId=<value> - Multiple:
?departmentId=<value1>&departmentId=<value2> - Null:
?departmentId=null
leaveType (String): Type of leave (e.g. vacation, sick, emergency).
- Single (partial match, case-insensitive):
?leaveType=<value> - Multiple:
?leaveType=<value1>&leaveType=<value2> - Null:
?leaveType=null
startDate (Date): First day of leave (inclusive).
- Single date:
?startDate=2024-01-15 - Multiple dates:
?startDate=2024-01-15&startDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?startDate=null
endDate (Date): Last day of leave (inclusive).
- Single date:
?endDate=2024-01-15 - Multiple dates:
?endDate=2024-01-15&endDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?endDate=null
status (Enum): Leave request status (pending, approved, rejected, cancelled).
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
REST Request To access the api you can use the REST controller with the path GET /v1/leaverequests
axios({
method: 'GET',
url: '/v1/leaverequests',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '<value>' // Filter by userId
// departmentId: '<value>' // Filter by departmentId
// leaveType: '<value>' // Filter by leaveType
// startDate: '<value>' // Filter by startDate
// endDate: '<value>' // Filter by endDate
// status: '<value>' // Filter by status
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequests",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"leaveRequests": [
{
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"department": [
null,
null,
null
],
"approver": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
List Myleaverequests API
List the currently logged-in user’s own leave requests. Always scoped to the authenticated user’s userId. Available to all roles.
API Frontend Description By The Backend Architect
- UX: Shows the logged-in user’s own leave requests with status, dates, and approver info. Supports pagination and sorting by most recent first.
Rest Route
The listMyLeaveRequests API REST controller can be triggered via the following route:
/v1/myleaverequests
Rest Request Parameters
Filter Parameters
The listMyLeaveRequests api supports 6 optional filter parameters for filtering list results:
userId (ID): ID of employee/user requesting leave (auth:user.id)
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
departmentId (ID): Department (userGroup) id, for scoping leave if relevant
- Single:
?departmentId=<value> - Multiple:
?departmentId=<value1>&departmentId=<value2> - Null:
?departmentId=null
leaveType (String): Type of leave (e.g. vacation, sick, emergency).
- Single (partial match, case-insensitive):
?leaveType=<value> - Multiple:
?leaveType=<value1>&leaveType=<value2> - Null:
?leaveType=null
startDate (Date): First day of leave (inclusive).
- Single date:
?startDate=2024-01-15 - Multiple dates:
?startDate=2024-01-15&startDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?startDate=null
endDate (Date): Last day of leave (inclusive).
- Single date:
?endDate=2024-01-15 - Multiple dates:
?endDate=2024-01-15&endDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?endDate=null
status (Enum): Leave request status (pending, approved, rejected, cancelled).
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
REST Request To access the api you can use the REST controller with the path GET /v1/myleaverequests
axios({
method: 'GET',
url: '/v1/myleaverequests',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '<value>' // Filter by userId
// departmentId: '<value>' // Filter by departmentId
// leaveType: '<value>' // Filter by leaveType
// startDate: '<value>' // Filter by startDate
// endDate: '<value>' // Filter by endDate
// status: '<value>' // Filter by status
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequests",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"leaveRequests": [
{
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"department": [
null,
null,
null
],
"approver": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
]
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Get Myleaverequest API
Retrieve the details of a single leave request by ID, scoped to the currently logged-in user. The user can only see their own leave request. Enriches response with user, department, and approver info.
API Frontend Description By The Backend Architect
- UX: Employee views their own leave request detail with full info. Enriched with user, department, and approver joins. Returns 404 if the record doesn’t exist or doesn’t belong to the logged-in user.
Rest Route
The getMyLeaveRequest API REST controller can be triggered via the following route:
/v1/myleaverequest/:leaveRequestId
Rest Request Parameters
The getMyLeaveRequest api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| leaveRequestId | ID | true | request.params?.[“leaveRequestId”] |
| leaveRequestId : 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/myleaverequest/:leaveRequestId
axios({
method: 'GET',
url: `/v1/myleaverequest/${leaveRequestId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "leaveRequest",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"leaveRequest": {
"id": "ID",
"userId": "ID",
"departmentId": "ID",
"requestDate": "Date",
"leaveType": "String",
"startDate": "Date",
"endDate": "Date",
"reason": "String",
"status": "Enum",
"status_idx": "Integer",
"approverId": "ID",
"approvedDate": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"user": {
"email": "String",
"fullname": "String",
"avatar": "String"
},
"approver": {
"email": "String",
"fullname": "String",
"avatar": "String"
}
}
}
After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 12 - PayrollReporting Service
This document is a part of a REST API guide for the workforceos 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 payrollReporting
Service Access
PayrollReporting service management is handled through service specific base urls.
PayrollReporting 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 payrollReporting service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/payrollreporting-api - Staging:
https://workforceos-stage.mindbricks.co/payrollreporting-api - Production:
https://workforceos.mindbricks.co/payrollreporting-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to payrollReporting service.
Scope
PayrollReporting Service Description
Handles payroll report records for employees based on calculated hours, overtime, absences from attendance/leave. Provides summary views by user/period/department, allows payment status entry (not processing). Employees can view their own reports. Company tenant scoped and RBAC-enforced.
PayrollReporting service provides apis and business logic for following data objects in workforceos 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.
payrollReport Data Object: Represents a calculated payroll report for a single employee and pay period. Contains total hours worked, overtime, absences, calculated salary based on shift attendance, bonuses/deductions, and manual payment status (no actual payment processing).
PayrollReporting Service Frontend Description By The Backend Architect
This service exposes all payroll calculation/reporting logic and APIs for frontend consumption. Payroll reports can be browsed by period, filtered by user/department. Employees see only their own reports; admins/managers may view/filter all for company or department. Payroll calculations always reflect real shift/attendance/leave data; bonus/deduction/payment status can be manually entered. Payroll rows/fields must not be edited except as per permissions, and updates are logged. Provide clear field-level UI and summary breakdowns in UX.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
PayrollReport Data Object
Represents a calculated payroll report for a single employee and pay period. Contains total hours worked, overtime, absences, calculated salary based on shift attendance, bonuses/deductions, and manual payment status (no actual payment processing).
PayrollReport Data Object Frontend Description By The Backend Architect
A single payroll report instance summarizes one employee’s working period, showing hours, overtime, paid absences, bonus and deduction fields, as well as manual payment status. Employees may view their own reports but only designated payroll admins/managers control updates to payment status. All main hour and absence fields are always calculated from system records—never entered manually. Each instance is uniquely defined by (userId, periodStart, periodEnd).
PayrollReport Data Object Properties
PayrollReport 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 | Reference to the user/employee this report summarizes (auth:user.id). |
periodStart |
Date | false | Yes | No | Start date of reporting/payroll period (inclusive). |
periodEnd |
Date | false | Yes | No | End date of the reporting/payroll period (inclusive). |
totalHoursWorked |
Double | false | Yes | No | Total hours worked during this period (summed from attendance data, auto-calculated). |
overtimeHours |
Double | false | Yes | No | Total overtime hours for period (auto-calculated from attendance, company policy). |
absenceDays |
Integer | false | Yes | No | Total days absent during period (from leave & attendance). Auto-calculated. |
bonus |
Double | false | No | No | Manual bonus to add for this period (optional entry by admin/manager only). |
deduction |
Double | false | No | No | Manual deduction for this period (optional entry by admin/manager only). |
salaryCalculated |
Double | false | Yes | No | Auto-calculated salary for the period: base salary, hours, overtime, bonuses, and deductions. Always calculated, never direct entry. |
paymentStatus |
Enum | false | Yes | No | Manual entry tracking payment status for this period (‘paid’, ‘unpaid’, ‘partial’, ‘pending’). |
paymentDate |
Date | false | No | No | Manual entry of actual date payment was made for this period (optional, admins/managers only). |
notes |
String | false | No | No | Optional notes (manual, internal)—remark/history on payment changes, bonuses, or irregularities. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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.
- paymentStatus: [paid, unpaid, partial, pending]
Relation Properties
userId
Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.
In frontend, please ensure that,
1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.
- userId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
Filter Properties
userId periodStart periodEnd paymentStatus companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
userId: ID has a filter named
userId -
periodStart: Date has a filter named
periodStart -
periodEnd: Date has a filter named
periodEnd -
paymentStatus: Enum has a filter named
paymentStatus -
companyId: ID has a filter named
companyId
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.
PayrollReport Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createPayrollReport |
/v1/payrollreports |
Yes |
| Update | updatePayrollReport |
/v1/payrollReports/:payrollReportId |
Yes |
| Delete | none | - | Auto |
| Get | getPayrollReport |
/v1/payrollReports/:payrollReportId |
Yes |
| List | listPayrollReports |
/v1/payrollreports |
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 Payrollreport API
[Default create API] — This is the designated default create API for the payrollReport data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Create a payroll report for a user and period; auto-calculates hours, overtime, absences, salary from attendance/leave. Allowed for admins/managers. Enforces report uniqueness and ownership. Manual entry only allowed for paymentStatus/bonus/deduction/notes (not raw hours/salary).
API Frontend Description By The Backend Architect
This API creates a payroll report for the chosen employee for a pay period, auto-deriving all work hour data from canonical attendance and leave logs. Admins/managers may set payment status, bonus, deduction and notes upon creation, but all time fields are system-calculated. Creating a payroll report when one exists for user/period will update the report (idempotent).
Rest Route
The createPayrollReport API REST controller can be triggered via the following route:
/v1/payrollreports
Rest Request Parameters
The createPayrollReport api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| userId | ID | true | request.body?.[“userId”] |
| periodStart | Date | true | request.body?.[“periodStart”] |
| periodEnd | Date | true | request.body?.[“periodEnd”] |
| bonus | Double | false | request.body?.[“bonus”] |
| deduction | Double | false | request.body?.[“deduction”] |
| notes | String | false | request.body?.[“notes”] |
| paymentStatus | Enum | false | request.body?.[“paymentStatus”] |
| paymentDate | Date | false | request.body?.[“paymentDate”] |
| userId : The userId for whom to generate the payroll report. | |||
| periodStart : Payroll period start date (inclusive). | |||
| periodEnd : Payroll period end date (inclusive). | |||
| bonus : Optional manual bonus. | |||
| deduction : Optional manual deduction. | |||
| notes : Notes for this payroll report. | |||
| paymentStatus : Manual status (paid, unpaid, partial, pending). | |||
| paymentDate : Manual date of payment, if any. |
REST Request To access the api you can use the REST controller with the path POST /v1/payrollreports
axios({
method: 'POST',
url: '/v1/payrollreports',
data: {
userId:"ID",
periodStart:"Date",
periodEnd:"Date",
bonus:"Double",
deduction:"Double",
notes:"String",
paymentStatus:"Enum",
paymentDate:"Date",
},
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.
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "payrollReport",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"payrollReport": {
"user": {
"fullname": "String",
"avatar": "String"
},
"isActive": true
}
}
Update Payrollreport API
[Default update API] — This is the designated default update API for the payrollReport data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Update paymentStatus/paymentDate, bonus, deduction, or notes for a payroll report. All worked hours/absence/salary remain auto-calculated. Only payroll admins/managers allowed. All changes are logged for audit.
API Frontend Description By The Backend Architect
Allows admins/managers to update the payment status, payment date, bonus, deduction, and report notes for an existing payroll period for an employee. No update to hours, absences, or salary is accepted directly (these remain auto-calculated on update). All updates are logged for audit trail. Editing salary must trigger recalculation with new bonuses/deductions if provided.
Rest Route
The updatePayrollReport API REST controller can be triggered via the following route:
/v1/payrollReports/:payrollReportId
Rest Request Parameters
The updatePayrollReport api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| payrollReportId | ID | true | request.params?.[“payrollReportId”] |
| bonus | Double | false | request.body?.[“bonus”] |
| deduction | Double | false | request.body?.[“deduction”] |
| notes | String | false | request.body?.[“notes”] |
| paymentStatus | Enum | false | request.body?.[“paymentStatus”] |
| paymentDate | Date | false | request.body?.[“paymentDate”] |
| payrollReportId : ID of payroll report to update. | |||
| bonus : Update bonus. | |||
| deduction : Update deduction. | |||
| notes : Update notes. | |||
| paymentStatus : Update payment status. | |||
| paymentDate : Update payment date. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/payrollReports/:payrollReportId
axios({
method: 'PATCH',
url: `/v1/payrollReports/${payrollReportId}`,
data: {
bonus:"Double",
deduction:"Double",
notes:"String",
paymentStatus:"Enum",
paymentDate:"Date",
},
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "payrollReport",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"payrollReport": {
"user": {
"fullname": "String",
"avatar": "String"
},
"isActive": true
}
}
Get Payrollreport API
[Default get API] — This is the designated default get API for the payrollReport data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get a specific payroll report and its calculated details for a pay period and employee. Employees may fetch only their own; admins/managers may fetch any for their company.
API Frontend Description By The Backend Architect
Fetches a payroll report for the given id. Enriches response with user (employee) summary, covering total hours, overtime, absences, salary, payment status and optional bonuses/deductions/notes. Employees can’t see reports not their own; admin/manager may fetch any within company.
Rest Route
The getPayrollReport API REST controller can be triggered via the following route:
/v1/payrollReports/:payrollReportId
Rest Request Parameters
The getPayrollReport api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| payrollReportId | ID | true | request.params?.[“payrollReportId”] |
| payrollReportId : ID of payroll report to fetch. |
REST Request To access the api you can use the REST controller with the path GET /v1/payrollReports/:payrollReportId
axios({
method: 'GET',
url: `/v1/payrollReports/${payrollReportId}`,
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "payrollReport",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"payrollReport": {
"user": {
"fullname": "String",
"avatar": "String"
},
"isActive": true
}
}
List Payrollreports API
[Default list API] — This is the designated default list API for the payrollReport data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List payroll reports for employees. Employees can view their own; managers/admins can filter and list by user/period/department for the company.
API Frontend Description By The Backend Architect
Lists all payroll reports accessible to the calling user in their company scope. Employees see only their own payroll history; company admins/managers can filter by user, payroll period, payment status for reporting or payroll review. Supports pagination and can be enriched per-user/department via selectJoin.
Rest Route
The listPayrollReports API REST controller can be triggered via the following route:
/v1/payrollreports
Rest Request Parameters
The listPayrollReports api has got 4 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| userId | ID | false | request.query?.[“userId”] |
| periodStart | Date | false | request.query?.[“periodStart”] |
| periodEnd | Date | false | request.query?.[“periodEnd”] |
| paymentStatus | Enum | false | request.query?.[“paymentStatus”] |
| userId : Filter by employee userId. | |||
| periodStart : Filter period - date on or after | |||
| periodEnd : Filter period - date on or before | |||
| paymentStatus : Filter by payment status. |
REST Request To access the api you can use the REST controller with the path GET /v1/payrollreports
axios({
method: 'GET',
url: '/v1/payrollreports',
data: {
},
params: {
userId:'"ID"',
periodStart:'"Date"',
periodEnd:'"Date"',
paymentStatus:'"Enum"',
}
});
REST Response
This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "payrollReports",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"payrollReports": [
{
"user": [
{
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 13 - AnnouncementManagement Service
This document is a part of a REST API guide for the workforceos 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 announcementManagement
Service Access
AnnouncementManagement service management is handled through service specific base urls.
AnnouncementManagement 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 announcementManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/announcementmanagement-api - Staging:
https://workforceos-stage.mindbricks.co/announcementmanagement-api - Production:
https://workforceos.mindbricks.co/announcementmanagement-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to announcementManagement service.
Scope
AnnouncementManagement Service Description
Handles company-wide and department-specific announcements, supporting scheduled or immediate delivery. Enables admins/managers to create, edit, and manage rich-text announcements, assign audience (all/company/department/users), and triggers events for notification delivery. Employees see relevant announcements in history/detail. Fully tenant-scoped.
AnnouncementManagement service provides apis and business logic for following data objects in workforceos 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.
announcement Data Object: A company announcement created by admin/manager for company- or department-wide communication. Supports scheduled (future) or immediate send, rich-text content, explicit audience assignment, and visibility expiry.
AnnouncementManagement Service Frontend Description By The Backend Architect
Announcement Management: UX Guide
- Announcements appear in a chronological feed; most recent and currently visible ones shown highest.
- Employee view: Only see announcements sent to your company, department, or user. Only active/visible announcements (status: sent, time within visibleUntil), oldest first by sendTime.
- Admin/manager view: Can view all, including scheduled/cancelled; can create, edit, and cancel announcements; UI for scheduling future announcements.
- Announcement details: Title, content (markdown/HTML rendered), target departments/users (display as readable lists), scheduled/delivery info, and creator. Render status badge: scheduled/sent/cancelled.
- Form supports rich text; on scheduling, select send time and visible until expiry if needed.
- Editing only allowed for scheduled/cancelled, not already sent announcements.
- Show recipients (departments/users) if set, otherwise say “All employees”.
- Immediate delivery = sendTime now.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
Announcement Data Object
A company announcement created by admin/manager for company- or department-wide communication. Supports scheduled (future) or immediate send, rich-text content, explicit audience assignment, and visibility expiry.
Announcement Data Object Frontend Description By The Backend Architect
- Rich-text content with support for HTML/markdown (render as message/policy/notification).
- Target audience: can be all, specific departments, or user list (null = all employees).
- Status: scheduled (if sendTime>now), sent (if sendTime<=now & delivered), cancelled (admin cancels or deletes).
- Announcements with sendTime in the future only visible to creators and admin/manager until sent.
- visibleUntil enables persistent/expiring announcements. Default to long expiry if not set.
- Recipients display as user/group names, or ‘All employees’ if neither array set.
Announcement Data Object Properties
Announcement 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 |
|---|---|---|---|---|---|
creatorId |
ID | false | Yes | No | auth:user.id - Creator of the announcement |
title |
String | false | Yes | No | Announcement subject/title (short display name). |
body |
Text | false | Yes | No | Announcement content body (markdown/HTML string). |
targetDepartmentIds |
ID | true | No | No | Department userGroup IDs (auth:userGroup.id) to target recipients. Null/empty means all departments. Used for scoping announcements to groups. |
audienceUserIds |
ID | true | No | No | Explicit user IDs (auth:user.id) to target (optional, null=all applicable). Used for targeting specific individuals only if needed. Supercedes departments if set. |
sendTime |
Date | false | Yes | No | Scheduled send time for the announcement (UTC). Immediate if now/past, future means scheduled/pending delivery. Used for status logic. |
visibleUntil |
Date | false | No | No | Optional. Announcements are visible until this date (expiry). If null, visible for a platform-defined default duration (e.g., 30/90 days, or forever). |
status |
Enum | false | Yes | No | Announcement status: scheduled (future, unsent); sent (visible/delivered); cancelled (withdrawn by admin/manager); status changes control delivery/event publishing. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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
targetDepartmentIds audienceUserIds
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.
- status: [scheduled, sent, cancelled]
Relation Properties
creatorId targetDepartmentIds audienceUserIds
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.
- creatorId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
- targetDepartmentIds: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- audienceUserIds: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
creatorId title sendTime status companyId
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.
-
creatorId: ID has a filter named
creatorId -
title: String has a filter named
title -
sendTime: Date has a filter named
sendTime -
status: Enum has a filter named
status -
companyId: ID has a filter named
companyId
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.
Announcement 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 | createAnnouncement |
/v1/announcements |
Yes |
| Update | updateAnnouncement |
/v1/announcements/:announcementId |
Yes |
| Delete | deleteAnnouncement |
/v1/announcements/:announcementId |
Yes |
| Get | getAnnouncement |
/v1/announcements/:announcementId |
Yes |
| List | listAnnouncements |
/v1/announcements |
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 Announcement API
[Default create API] — This is the designated default create API for the announcement data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Admins/managers create a new announcement for company or targeted audience. Supports scheduled and immediate announcements. Upon creation, if sendTime <= now and not cancelled, triggers event for notification delivery.
API Frontend Description By The Backend Architect
- Only admin/manager can create. Form includes: title, body (rich text), recipient selection (departments/users or all), sendTime (date/time), optional visibleUntil.
- Immediate = sendTime now. Scheduled = in future; shows in creator/admin list but not to employees until time.
- After creation, display confirmation and status: scheduled or sent. Cannot edit once sent.
- Employee audience calculated based on fields. All fields validated in backend.
Rest Route
The createAnnouncement API REST controller can be triggered via the following route:
/v1/announcements
Rest Request Parameters
The createAnnouncement api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| title | String | true | request.body?.[“title”] |
| body | Text | true | request.body?.[“body”] |
| targetDepartmentIds | ID | false | request.body?.[“targetDepartmentIds”] |
| audienceUserIds | ID | false | request.body?.[“audienceUserIds”] |
| sendTime | Date | true | request.body?.[“sendTime”] |
| visibleUntil | Date | false | request.body?.[“visibleUntil”] |
| title : Announcement subject/title (short display name). | |||
| body : Announcement content body (markdown/HTML string). | |||
| targetDepartmentIds : Department userGroup IDs (auth:userGroup.id) to target recipients. Null/empty means all departments. Used for scoping announcements to groups. | |||
| audienceUserIds : Explicit user IDs (auth:user.id) to target (optional, null=all applicable). Used for targeting specific individuals only if needed. Supercedes departments if set. | |||
| sendTime : Scheduled send time for the announcement (UTC). Immediate if now/past, future means scheduled/pending delivery. Used for status logic. | |||
| visibleUntil : Optional. Announcements are visible until this date (expiry). If null, visible for a platform-defined default duration (e.g., 30/90 days, or forever). |
REST Request To access the api you can use the REST controller with the path POST /v1/announcements
axios({
method: 'POST',
url: '/v1/announcements',
data: {
title:"String",
body:"Text",
targetDepartmentIds:"ID",
audienceUserIds:"ID",
sendTime:"Date",
visibleUntil:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "announcement",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"announcement": {
"id": "ID",
"creatorId": "ID",
"title": "String",
"body": "Text",
"targetDepartmentIds": "ID",
"audienceUserIds": "ID",
"sendTime": "Date",
"visibleUntil": "Date",
"status": "Enum",
"status_idx": "Integer",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Announcement API
[Default update API] — This is the designated default update API for the announcement data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Admins/managers update a scheduled/cancelled announcement. Not allowed if already sent. If sendTime changes to now or past, triggers sent event and status update on save.
API Frontend Description By The Backend Architect
- Admin/manager may edit scheduled/cancelled announcement fields, not already sent ones.
- Any change in sendTime/visibleUntil modifies delivery schedule, triggers event if status becomes ‘sent’.
- UI disables editing of sent announcements.
Rest Route
The updateAnnouncement API REST controller can be triggered via the following route:
/v1/announcements/:announcementId
Rest Request Parameters
The updateAnnouncement api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| announcementId | ID | true | request.params?.[“announcementId”] |
| title | String | false | request.body?.[“title”] |
| body | Text | false | request.body?.[“body”] |
| targetDepartmentIds | ID | false | request.body?.[“targetDepartmentIds”] |
| audienceUserIds | ID | false | request.body?.[“audienceUserIds”] |
| sendTime | Date | true | request.body?.[“sendTime”] |
| visibleUntil | Date | false | request.body?.[“visibleUntil”] |
| announcementId : This id paremeter is used to select the required data object that will be updated | |||
| title : Announcement subject/title (short display name). | |||
| body : Announcement content body (markdown/HTML string). | |||
| targetDepartmentIds : Department userGroup IDs (auth:userGroup.id) to target recipients. Null/empty means all departments. Used for scoping announcements to groups. | |||
| audienceUserIds : Explicit user IDs (auth:user.id) to target (optional, null=all applicable). Used for targeting specific individuals only if needed. Supercedes departments if set. | |||
| sendTime : Scheduled send time for the announcement (UTC). Immediate if now/past, future means scheduled/pending delivery. Used for status logic. | |||
| visibleUntil : Optional. Announcements are visible until this date (expiry). If null, visible for a platform-defined default duration (e.g., 30/90 days, or forever). |
REST Request To access the api you can use the REST controller with the path PATCH /v1/announcements/:announcementId
axios({
method: 'PATCH',
url: `/v1/announcements/${announcementId}`,
data: {
title:"String",
body:"Text",
targetDepartmentIds:"ID",
audienceUserIds:"ID",
sendTime:"Date",
visibleUntil:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "announcement",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"announcement": {
"id": "ID",
"creatorId": "ID",
"title": "String",
"body": "Text",
"targetDepartmentIds": "ID",
"audienceUserIds": "ID",
"sendTime": "Date",
"visibleUntil": "Date",
"status": "Enum",
"status_idx": "Integer",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Announcement API
[Default delete API] — This is the designated default delete API for the announcement data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Soft delete (mark as cancelled) for scheduled/cancelled announcements. Sent announcements cannot be deleted.
API Frontend Description By The Backend Architect
Admins/managers can cancel (soft delete) announcements that have not been sent yet; sent announcements stay in history, cannot be deleted for auditability/accountability.
Rest Route
The deleteAnnouncement API REST controller can be triggered via the following route:
/v1/announcements/:announcementId
Rest Request Parameters
The deleteAnnouncement api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| announcementId | ID | true | request.params?.[“announcementId”] |
| announcementId : 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/announcements/:announcementId
axios({
method: 'DELETE',
url: `/v1/announcements/${announcementId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "announcement",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"announcement": {
"id": "ID",
"creatorId": "ID",
"title": "String",
"body": "Text",
"targetDepartmentIds": "ID",
"audienceUserIds": "ID",
"sendTime": "Date",
"visibleUntil": "Date",
"status": "Enum",
"status_idx": "Integer",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Announcement API
[Default get API] — This is the designated default get API for the announcement data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get details of a single announcement if user is within company and eligible audience. Employees see only those sent & visible; admins/managers see all for own company.
API Frontend Description By The Backend Architect
- Employees: Fetch detail for announcement if status is ‘sent’, now is after sendTime, current user is in audience or target department or (if both empty) all employees. Not allowed for other companies.
- Admin/manager: May see any in company (scheduled, sent, cancelled).
- Response enriches creator and department names via join.
Rest Route
The getAnnouncement API REST controller can be triggered via the following route:
/v1/announcements/:announcementId
Rest Request Parameters
The getAnnouncement api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| announcementId | ID | true | request.params?.[“announcementId”] |
| announcementId : 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/announcements/:announcementId
axios({
method: 'GET',
url: `/v1/announcements/${announcementId}`,
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "announcement",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"announcement": {
"creator": {
"email": "String",
"fullname": "String",
"avatar": "String"
},
"departments": [
null,
null,
null
],
"isActive": true
}
}
List Announcements API
[Default list API] — This is the designated default list API for the announcement data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List announcements visible to user: employees get only those sent and addressed to their dept/user/all; admin/manager see all for their company; sorted by sendTime desc.
API Frontend Description By The Backend Architect
- Employee list: Only current and past (‘sent’, sendTime <= now), not cancelled, visible to you (company and audience/department match or all employees).
- Admin/manager list: See all announcements for company, including scheduled/cancelled/sent; use column filter to toggle status/audience; default sort is sendTime desc.
- Each entry shows: title, short preview, status, creator, send time, and expiry. Allow filter by status, sendTime, department, creator.
Rest Route
The listAnnouncements API REST controller can be triggered via the following route:
/v1/announcements
Rest Request Parameters
The listAnnouncements api has got no request parameters.
REST Request To access the api you can use the REST controller with the path GET /v1/announcements
axios({
method: 'GET',
url: '/v1/announcements',
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "announcements",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"announcements": [
{
"creator": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"departments": [
null,
null,
null
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Process Scheduledannouncements API
Background job that runs every minute to check for scheduled announcements whose sendTime has passed and updates their status to ‘sent’. This triggers the announcement.sent event for notification delivery.
API Frontend Description By The Backend Architect
Internal cron job - no frontend endpoint. Runs automatically every minute to process scheduled announcements.
Rest Route
The processScheduledAnnouncements API REST controller can be triggered via the following route:
/v1/processscheduledannouncements
Rest Request Parameters
Filter Parameters
The processScheduledAnnouncements api supports 4 optional filter parameters for filtering list results:
creatorId (ID): auth:user.id - Creator of the announcement
- Single:
?creatorId=<value> - Multiple:
?creatorId=<value1>&creatorId=<value2> - Null:
?creatorId=null
title (String): Announcement subject/title (short display name).
- Single (partial match, case-insensitive):
?title=<value> - Multiple:
?title=<value1>&title=<value2> - Null:
?title=null
sendTime (Date): Scheduled send time for the announcement (UTC). Immediate if now/past, future means scheduled/pending delivery. Used for status logic.
- Single date:
?sendTime=2024-01-15 - Multiple dates:
?sendTime=2024-01-15&sendTime=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?sendTime=null
status (Enum): Announcement status: scheduled (future, unsent); sent (visible/delivered); cancelled (withdrawn by admin/manager); status changes control delivery/event publishing.
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
REST Request To access the api you can use the REST controller with the path GET /v1/processscheduledannouncements
axios({
method: 'GET',
url: '/v1/processscheduledannouncements',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// creatorId: '<value>' // Filter by creatorId
// title: '<value>' // Filter by title
// sendTime: '<value>' // Filter by sendTime
// status: '<value>' // Filter by status
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "announcements",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"announcements": [
{
"id": "ID",
"creatorId": "ID",
"title": "String",
"body": "Text",
"targetDepartmentIds": "ID",
"audienceUserIds": "ID",
"sendTime": "Date",
"visibleUntil": "Date",
"status": "Enum",
"status_idx": "Integer",
"companyId": "ID",
"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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 14 - AiWorkforceAnalytics Service
This document is a part of a REST API guide for the workforceos 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 aiWorkforceAnalytics
Service Access
AiWorkforceAnalytics service management is handled through service specific base urls.
AiWorkforceAnalytics 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 aiWorkforceAnalytics service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/aiworkforceanalytics-api - Staging:
https://workforceos-stage.mindbricks.co/aiworkforceanalytics-api - Production:
https://workforceos.mindbricks.co/aiworkforceanalytics-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to aiWorkforceAnalytics service.
Scope
AiWorkforceAnalytics Service Description
Microservice for computing and delivering AI-powered workforce analytics (e.g., shift optimization, absenteeism insights, staffing trends) for eligible (subscribed) companies. Handles insight calculation, storage, and secure distribution to authorized users. Publishes insight alerts/events for notifications. Strictly enforces company data isolation and subscription gating on all features.
AiWorkforceAnalytics service provides apis and business logic for following data objects in workforceos 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.
aiInsight Data Object: Represents an AI-generated insight, analytic, or tip for a company (and optionally individual user) for a specific period/type. Used for staffing recommendations, absenteeism patterns, productivity, and targeted advice. Stores computed detail as JSON and current delivery/processing status.
AiWorkforceAnalytics Service Frontend Description By The Backend Architect
aiWorkforceAnalytics Service - FE Prompt
This service exposes APIs and (optionally) AI endpoints for accessing company-level and personal AI-powered workforce insights. All access is strictly RBAC and company-tenant isolated. Insights may be addressed to admins/managers (e.g., operational or team trends) or to employees (personal tips/alerts). For dashboards and widgets, use listAiInsights (with appropriate filters by period, type, or recipient), and for detail, use getAiInsight.
Frontends must ensure they handle and display only those insights the authenticated user is authorized for (e.g., an employee sees only their tips/alerts by id, not company/department ones).
API Structure
Object Structure of a Successful Response
When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.
HTTP Status Codes:
- 200 OK: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully.
- 201 Created: Returned for CREATE operations, indicating that the resource was created successfully.
Success Response Format:
For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
AiInsight Data Object
Represents an AI-generated insight, analytic, or tip for a company (and optionally individual user) for a specific period/type. Used for staffing recommendations, absenteeism patterns, productivity, and targeted advice. Stores computed detail as JSON and current delivery/processing status.
AiInsight Data Object Frontend Description By The Backend Architect
When presenting an aiInsight: show title (based on type), summary preview (from details), and period. For admins/managers, show all for their company; for employees, only those addressed to them (audienceUserId). Include a details view with interpretation of the insight data (e.g., charts if possible). DeliveredTime indicates when it was made available.
AiInsight Data Object Properties
AiInsight 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 |
|---|---|---|---|---|---|
insightType |
String | false | Yes | No | Type/classification of the insight (e.g. ‘staffingPrediction’, ‘absenteeismPattern’, ‘shiftAnomaly’, ‘productivityTip’). |
audienceUserId |
ID | false | No | No | If present, insight is for a specific employee; otherwise company/manager-level. |
applicablePeriod |
Object | false | Yes | No | Date range period to which the insight applies (object: {startDate, endDate}) |
details |
Text | false | Yes | No | JSON-stringified blob containing the AI result, message, chart data, or recommendation. |
aiStatus |
Enum | false | Yes | No | Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed). |
deliveredTime |
Date | false | No | No | Actual delivery/publication time (set when status becomes ‘delivered’); null when pending. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- 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.
- aiStatus: [pending, delivered, error]
Relation Properties
audienceUserId
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.
- audienceUserId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
Filter Properties
insightType audienceUserId applicablePeriod aiStatus companyId
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.
-
insightType: String has a filter named
insightType -
audienceUserId: ID has a filter named
audienceUserId -
applicablePeriod: Object has a filter named
applicablePeriod -
aiStatus: Enum has a filter named
aiStatus -
companyId: ID has a filter named
companyId
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.
AiInsight Default APIs
Display Label Property: insightType — 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 | createAiInsight |
/v1/aiinsights |
Yes |
| Update | updateAiInsight |
/v1/aiinsights/:aiInsightId |
Yes |
| Delete | none | - | Auto |
| Get | getAiInsight |
/v1/insights/:id |
Yes |
| List | listAiInsights |
/v1/insights |
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.
AI Agents
This service exposes 1 AI agent as dedicated API endpoints. Each agent is a backend-managed AI pipeline with its own model, system prompt, and optional tool access. The frontend interacts with agents through standard HTTP requests — either synchronous REST calls or streaming SSE connections.
Agent Overview
| Agent | Modality | Mode | REST | SSE | Auth | Path |
|---|---|---|---|---|---|---|
insightGenerator |
text | task | Yes | Yes | Yes | /ai-insight/generate |
Agent: insightGenerator
AI agent for generating company workforce insights. Accesses all company data (employees, departments, attendance, tasks, leave) to provide contextual answers based on actual company data. For general workforce questions, provides general advice. For company-specific questions, analyzes the data and provides data-driven insights.
- Modality:
text— text-in, text-out - Execution Mode:
task— single request/response (one-shot) - Provider / Model:
openai/gpt-4o - Response Format:
json - Token Budget: 5000
- Timeout: 120000ms
REST Endpoint (Synchronous)
POST {baseUrl}/ai-insight/generate
Authorization: Bearer {accessToken}
Content-Type: application/json
Request Body:
{
"prompt": "Your message or instruction to the agent"
}
Response:
{
"success": true,
"data": {
"response": "Agent response text"
}
}
SSE Endpoint (Streaming)
POST {baseUrl}/ai-insight/generate/stream
Authorization: Bearer {accessToken}
Content-Type: application/json
The request body is the same as the REST endpoint. The response is a Server-Sent Events stream:
event: chunk
data: {"content":"partial response text..."}
event: chunk
data: {"content":"more text..."}
event: complete
data: {}
Frontend integration pattern:
const response = await fetch(`${baseUrl}/ai-insight/generate/stream`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'mbx-company-codename': tenantCodename,
},
body: JSON.stringify({ prompt: userMessage }),
});
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 lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6));
if (data.content) {
// Append data.content to UI (streaming text)
}
}
}
}
API Reference
Create Aiinsight API
[Default create API] — This is the designated default create API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Internal/system API to create a new AI insight record for a company and period (typically used by AI agents or cron jobs, not direct user input). Requires that company has an active AI subscription. Sets status to pending; downstream process delivers and updates status.
API Frontend Description By The Backend Architect
Not a user-facing API. Used by the platform for inserting new insight data for later dashboard/alert delivery.
Rest Route
The createAiInsight API REST controller can be triggered via the following route:
/v1/aiinsights
Rest Request Parameters
The createAiInsight api has got 6 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| insightType | String | true | request.body?.[“insightType”] |
| audienceUserId | ID | false | request.body?.[“audienceUserId”] |
| applicablePeriod | Object | true | request.body?.[“applicablePeriod”] |
| details | Text | true | request.body?.[“details”] |
| aiStatus | Enum | true | request.body?.[“aiStatus”] |
| deliveredTime | Date | false | request.body?.[“deliveredTime”] |
| insightType : Type/classification of the insight (e.g. ‘staffingPrediction’, ‘absenteeismPattern’, ‘shiftAnomaly’, ‘productivityTip’). | |||
| audienceUserId : If present, insight is for a specific employee; otherwise company/manager-level. | |||
| applicablePeriod : Date range period to which the insight applies (object: {startDate, endDate}) | |||
| details : JSON-stringified blob containing the AI result, message, chart data, or recommendation. | |||
| aiStatus : Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed). | |||
| deliveredTime : Actual delivery/publication time (set when status becomes ‘delivered’); null when pending. |
REST Request To access the api you can use the REST controller with the path POST /v1/aiinsights
axios({
method: 'POST',
url: '/v1/aiinsights',
data: {
insightType:"String",
audienceUserId:"ID",
applicablePeriod:"Object",
details:"Text",
aiStatus:"Enum",
deliveredTime:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsight",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"aiInsight": {
"id": "ID",
"insightType": "String",
"audienceUserId": "ID",
"applicablePeriod": "Object",
"details": "Text",
"aiStatus": "Enum",
"aiStatus_idx": "Integer",
"deliveredTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Aiinsight API
[Default update API] — This is the designated default update API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Internal/system API for updating an existing AI insight (e.g., set as delivered, correction, or error annotation). Requires AI subscription. Used by scheduled delivery jobs, agent code, or admin.
API Frontend Description By The Backend Architect
Used internally to update AI insight status, e.g. after delivery or error. Not end-user facing.
Rest Route
The updateAiInsight API REST controller can be triggered via the following route:
/v1/aiinsights/:aiInsightId
Rest Request Parameters
The updateAiInsight api has got 7 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| aiInsightId | ID | true | request.params?.[“aiInsightId”] |
| insightType | String | false | request.body?.[“insightType”] |
| audienceUserId | ID | false | request.body?.[“audienceUserId”] |
| applicablePeriod | Object | false | request.body?.[“applicablePeriod”] |
| details | Text | false | request.body?.[“details”] |
| aiStatus | Enum | false | request.body?.[“aiStatus”] |
| deliveredTime | Date | false | request.body?.[“deliveredTime”] |
| aiInsightId : This id paremeter is used to select the required data object that will be updated | |||
| insightType : Type/classification of the insight (e.g. ‘staffingPrediction’, ‘absenteeismPattern’, ‘shiftAnomaly’, ‘productivityTip’). | |||
| audienceUserId : If present, insight is for a specific employee; otherwise company/manager-level. | |||
| applicablePeriod : Date range period to which the insight applies (object: {startDate, endDate}) | |||
| details : JSON-stringified blob containing the AI result, message, chart data, or recommendation. | |||
| aiStatus : Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed). | |||
| deliveredTime : Actual delivery/publication time (set when status becomes ‘delivered’); null when pending. |
REST Request To access the api you can use the REST controller with the path ** /v1/aiinsights/:aiInsightId**
axios({
method: '',
url: `/v1/aiinsights/${aiInsightId}`,
data: {
insightType:"String",
audienceUserId:"ID",
applicablePeriod:"Object",
details:"Text",
aiStatus:"Enum",
deliveredTime:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsight",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"aiInsight": {
"id": "ID",
"insightType": "String",
"audienceUserId": "ID",
"applicablePeriod": "Object",
"details": "Text",
"aiStatus": "Enum",
"aiStatus_idx": "Integer",
"deliveredTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Aiinsight API
[Default get API] — This is the designated default get API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Get a detailed AI insight for dashboards or notification rendering. Only accessible to: admin/manager of company, or employee for their tips (audienceUserId matches requester) AND company has active subscription.
API Frontend Description By The Backend Architect
FE must use this API to show a detailed AI insight. Employees may only see their own tips (if audienceUserId matches their userId), admin/managers may see all for their company.
Rest Route
The getAiInsight API REST controller can be triggered via the following route:
/v1/insights/:id
Rest Request Parameters
The getAiInsight api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| aiInsightId | ID | true | request.params?.[“aiInsightId”] |
| id | String | true | request.params?.[“id”] |
| aiInsightId : This id paremeter is used to query the required data object. | |||
| id : This parameter will be used to select the data object that is queried |
REST Request To access the api you can use the REST controller with the path GET /v1/insights/:id
axios({
method: 'GET',
url: `/v1/insights/${id}`,
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsight",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"aiInsight": {
"audienceUser": {
"email": "String",
"fullname": "String",
"avatar": "String"
},
"isActive": true
}
}
List Aiinsights API
[Default list API] — This is the designated default list API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations.
List all accessible AI insights for dashboards or user tip listings, scoped by role and audienceUserId, and company subscription. Filter by type, status, period.
API Frontend Description By The Backend Architect
Use this API to build an AI insights dashboard for company (admin/manager: all insights; employee: only their own or broadcast tips). Use filters as appropriate for time/type/audience. UI must show no data if company is not subscribed.
Rest Route
The listAiInsights API REST controller can be triggered via the following route:
/v1/insights
Rest Request Parameters
The listAiInsights api has got no request parameters.
REST Request To access the api you can use the REST controller with the path GET /v1/insights
axios({
method: 'GET',
url: '/v1/insights',
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.
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsights",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"aiInsights": [
{
"audienceUser": [
{
"email": "String",
"fullname": "String",
"avatar": "String"
},
{},
{}
],
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Delete Aiinsight API
Delete (soft) an AI insight. Only allowed for superAdmin/saasAdmin or tenantOwner/admin for own tenant, in error/cancel scenarios. Not a standard operational API.
API Frontend Description By The Backend Architect
Not end user facing—admin tool for error/corrections only.
Rest Route
The deleteAiInsight API REST controller can be triggered via the following route:
/v1/aiinsights/:aiInsightId
Rest Request Parameters
The deleteAiInsight api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| aiInsightId | ID | true | request.params?.[“aiInsightId”] |
| aiInsightId : 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 ** /v1/aiinsights/:aiInsightId**
axios({
method: '',
url: `/v1/aiinsights/${aiInsightId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsight",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"aiInsight": {
"id": "ID",
"insightType": "String",
"audienceUserId": "ID",
"applicablePeriod": "Object",
"details": "Text",
"aiStatus": "Enum",
"aiStatus_idx": "Integer",
"deliveredTime": "Date",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Save Insight API
Saves an AI workforce insight from stream conversation to database for history tracking
Rest Route
The saveInsight API REST controller can be triggered via the following route:
/v1/saveinsight
Rest Request Parameters
The saveInsight api has got 13 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| title | String | true | request.body?.[“title”] |
| summary | String | true | request.body?.[“summary”] |
| insightType | String | true | request.body?.[“insightType”] |
| audienceType | String | true | request.body?.[“audienceType”] |
| chart | Object | false | request.body?.[“chart”] |
| data | Object | false | request.body?.[“data”] |
| suggestion | String | false | request.body?.[“suggestion”] |
| period | String | false | request.body?.[“period”] |
| audienceUserId | String | false | request.body?.[“audienceUserId”] |
| applicablePeriod | Object | true | request.body?.[“applicablePeriod”] |
| details | Text | true | request.body?.[“details”] |
| aiStatus | Enum | true | request.body?.[“aiStatus”] |
| deliveredTime | Date | false | request.body?.[“deliveredTime”] |
| title : Insight title from AI stream | |||
| summary : Insight summary from AI stream | |||
| insightType : Type of insight (shift_optimization, absenteeism_alert, etc.) | |||
| audienceType : Target audience (admin, manager, employee, company) | |||
| chart : Optional chart data from AI | |||
| data : Additional data from AI insight | |||
| suggestion : AI suggestion/recommendation | |||
| period : Time period for the insight | |||
| audienceUserId : Specific user ID if personalized | |||
| applicablePeriod : Date range period to which the insight applies (object: {startDate, endDate}) | |||
| details : JSON-stringified blob containing the AI result, message, chart data, or recommendation. | |||
| aiStatus : Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed). | |||
| deliveredTime : Actual delivery/publication time (set when status becomes ‘delivered’); null when pending. |
REST Request To access the api you can use the REST controller with the path POST /v1/saveinsight
axios({
method: 'POST',
url: '/v1/saveinsight',
data: {
title:"String",
summary:"String",
insightType:"String",
audienceType:"String",
chart:"Object",
data:"Object",
suggestion:"String",
period:"String",
audienceUserId:"String",
applicablePeriod:"Object",
details:"Text",
aiStatus:"Enum",
deliveredTime:"Date",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsight",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"aiInsight": {
"id": "ID",
"insightType": "String",
"audienceUserId": "ID",
"applicablePeriod": "Object",
"details": "Text",
"aiStatus": "Enum",
"aiStatus_idx": "Integer",
"deliveredTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Save Aiinsight API
Saves an AI workforce insight from stream conversation to database for history tracking
Rest Route
The saveAiInsight API REST controller can be triggered via the following route:
/v1/save-insight
Rest Request Parameters
The saveAiInsight api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| insightType | String | false | request.body?.[“insightType”] |
| insightType : Type of insight (auto-detected by AI agent) |
REST Request To access the api you can use the REST controller with the path POST /v1/save-insight
axios({
method: 'POST',
url: '/v1/save-insight',
data: {
insightType:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "aiInsight",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"aiInsight": {
"id": "ID",
"insightType": "String",
"audienceUserId": "ID",
"applicablePeriod": "Object",
"details": "Text",
"aiStatus": "Enum",
"aiStatus_idx": "Integer",
"deliveredTime": "Date",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 15 - SubscriptionManagement Service
This document is a part of a REST API guide for the workforceos 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 subscriptionManagement
Service Access
SubscriptionManagement service management is handled through service specific base urls.
SubscriptionManagement 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 subscriptionManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/subscriptionmanagement-api - Staging:
https://workforceos-stage.mindbricks.co/subscriptionmanagement-api - Production:
https://workforceos.mindbricks.co/subscriptionmanagement-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to subscriptionManagement service.
Scope
SubscriptionManagement Service Description
Manages company AI subscriptions through Stripe payments. Companies must pay via Stripe to activate AI features—no manual subscription creation allowed. Handles the full Stripe payment lifecycle: checkout, payment confirmation, activation, and cancellation. The subscription status is entirely driven by Stripe webhook events. SuperAdmin/saasAdmin bypass payment for platform management.
SubscriptionManagement service provides apis and business logic for following data objects in workforceos 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.
companySubscription Data Object: Represents a company’s active or inactive subscription record for feature gating (AI, analytics, etc.). Used to track activation/expiry, status, available features, and audit trail of renewals. 1 per company; used for entitlement checking.
sys_companySubscriptionPayment Data Object: A payment storage object to store the payment life cyle of orders based on companySubscription object. It is autocreated based on the source object’s checkout config
sys_paymentCustomer Data Object: A payment storage object to store the customer values of the payment platform
sys_paymentMethod Data Object: A payment storage object to store the payment methods of the platform customers
SubscriptionManagement Service Frontend Description By The Backend Architect
This service handles AI subscription payments. Company admins (tenantOwner/tenantAdmin) initiate a subscription via createCompanySubscription, which triggers a Stripe checkout. After payment, the subscription becomes active automatically. Users can cancel via cancelCompanySubscription. No manual status changes allowed—everything is Stripe-driven. The frontend should show a ‘Subscribe to AI’ button that calls create, then redirects to the Stripe checkout URL from the response. Show subscription status from getCompanySubscription. Show a ‘Cancel’ button that calls cancelCompanySubscription.
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:
{
"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.
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
CompanySubscription Data Object
Represents a company’s active or inactive subscription record for feature gating (AI, analytics, etc.). Used to track activation/expiry, status, available features, and audit trail of renewals. 1 per company; used for entitlement checking.
CompanySubscription Data Object Frontend Description By The Backend Architect
This represents a company’s subscription status and feature access. Each company should have at most 1 active record; only admins can view or update it. The properties reflect when the subscription starts/ends, current status (active/pending/expired), feature entitlements, and audit trail (last renewed by whom). Subscription status is used by all frontend modules to determine access to AI/analytics panels. Employees cannot access this object directly; only admins see/edit (via admin views or SaaS support dashboards).
CompanySubscription Data Object Properties
CompanySubscription 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 |
|---|---|---|---|---|---|
activationDate |
Date | false | Yes | No | Start date/time when subscription is (re)activated. |
expiryDate |
Date | false | Yes | No | Planned end date/time of subscription validity (inclusive). |
status |
Enum | false | Yes | No | Subscription status: active, inactive, pending, or expired. |
subscribedFeatures |
String | true | No | No | Array of enabled feature flags for this company’s subscription (e.g., aiAnalytics, reporting, notifications). |
lastRenewedBy |
ID | false | No | No | ID of user (admin/mod) who last renewed or updated the subscription record; for audit. |
currency |
String | false | No | No | ISO currency code for the subscription payment. Defaults to usd. |
paymentStatus |
Enum | false | Yes | No | Stripe payment status: pending (awaiting payment), paid (success), failed, canceled. |
paymentStatusUpdatedAt |
Date | false | No | No | Timestamp of the last payment status change from Stripe. |
ownerId |
ID | false | Yes | No | The user who initiated the subscription purchase. Used for Stripe payment ownership. |
stripeSubscriptionId |
String | false | No | No | Stripe subscription ID for recurring billing management. Set after successful payment. |
amount |
Integer | false | Yes | No | Subscription price in cents (e.g. 4999 = $49.99). Used by Stripe payment flow. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
paymentConfirmation |
Enum | false | Yes | No | An automatic property that is used to check the confirmed status of the payment set by webhooks. |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set.
Array Properties
subscribedFeatures
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.
-
status: [active, inactive, pending, expired]
-
paymentStatus: [pending, paid, failed, canceled]
-
paymentConfirmation: [pending, processing, paid, canceled]
Relation Properties
lastRenewedBy ownerId
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.
- lastRenewedBy: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: No
- ownerId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
Required: Yes
Filter Properties
activationDate expiryDate status paymentStatus companyId paymentConfirmation
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
activationDate: Date has a filter named
activationDate -
expiryDate: Date has a filter named
expiryDate -
status: Enum has a filter named
status -
paymentStatus: Enum has a filter named
paymentStatus -
companyId: ID has a filter named
companyId -
paymentConfirmation: Enum has a filter named
paymentConfirmation
Sys_companySubscriptionPayment Data Object
A payment storage object to store the payment life cyle of orders based on companySubscription object. It is autocreated based on the source object’s checkout config
Sys_companySubscriptionPayment Data Object Properties
Sys_companySubscriptionPayment data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.
| Property | Type | IsArray | Required | Secret | Description |
|---|---|---|---|---|---|
ownerId |
ID | false | No | No | An ID value to represent owner user who created the order |
orderId |
ID | false | Yes | No | an ID value to represent the orderId which is the ID parameter of the source companySubscription object |
paymentId |
String | false | Yes | No | A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type |
paymentStatus |
String | false | Yes | No | A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. |
statusLiteral |
String | false | Yes | No | A string value to represent the logical payment status which belongs to the application lifecycle itself. |
redirectUrl |
String | false | No | No | A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set.
Filter Properties
ownerId orderId paymentId paymentStatus statusLiteral redirectUrl companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
ownerId: ID has a filter named
ownerId -
orderId: ID has a filter named
orderId -
paymentId: String has a filter named
paymentId -
paymentStatus: String has a filter named
paymentStatus -
statusLiteral: String has a filter named
statusLiteral -
redirectUrl: String has a filter named
redirectUrl -
companyId: ID has a filter named
companyId
Sys_paymentCustomer Data Object
A payment storage object to store the customer values of the payment platform
Sys_paymentCustomer Data Object Properties
Sys_paymentCustomer data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.
| Property | Type | IsArray | Required | Secret | Description |
|---|---|---|---|---|---|
userId |
ID | false | No | No | An ID value to represent the user who is created as a stripe customer |
customerId |
String | false | Yes | No | A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway |
platform |
String | false | Yes | No | A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set.
Filter Properties
userId customerId platform companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
userId: ID has a filter named
userId -
customerId: String has a filter named
customerId -
platform: String has a filter named
platform -
companyId: ID has a filter named
companyId
Sys_paymentMethod Data Object
A payment storage object to store the payment methods of the platform customers
Sys_paymentMethod Data Object Properties
Sys_paymentMethod data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.
| Property | Type | IsArray | Required | Secret | Description |
|---|---|---|---|---|---|
paymentMethodId |
String | false | Yes | No | A string value to represent the id of the payment method on the payment platform. |
userId |
ID | false | Yes | No | An ID value to represent the user who owns the payment method |
customerId |
String | false | Yes | No | A string value to represent the customer id which is generated on the payment gateway. |
cardHolderName |
String | false | No | No | A string value to represent the name of the card holder. It can be different than the registered customer. |
cardHolderZip |
String | false | No | No | A string value to represent the zip code of the card holder. It is used for address verification in specific countries. |
platform |
String | false | Yes | No | A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future. |
cardInfo |
Object | false | Yes | No | A Json value to store the card details of the payment method. |
companyId |
ID | false | Yes | No | An ID value to represent the tenant id of the company |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set.
Filter Properties
paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.
-
paymentMethodId: String has a filter named
paymentMethodId -
userId: ID has a filter named
userId -
customerId: String has a filter named
customerId -
cardHolderName: String has a filter named
cardHolderName -
cardHolderZip: String has a filter named
cardHolderZip -
platform: String has a filter named
platform -
cardInfo: Object has a filter named
cardInfo -
companyId: ID has a filter named
companyId
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.
CompanySubscription Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createCompanySubscription |
/v1/companysubscriptions |
Yes |
| Update | updateCompanySubscription |
/v1/companysubscriptions/:companySubscriptionId |
Yes |
| Delete | deleteCompanySubscription |
/v1/companysubscriptions/:companySubscriptionId |
Yes |
| Get | getCompanySubscription |
/v1/companysubscriptions/:companySubscriptionId |
Yes |
| List | listCompanySubscriptions |
/v1/companysubscriptions |
Yes |
Sys_companySubscriptionPayment Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | createCompanySubscriptionPayment |
/v1/companysubscriptionpayment |
Auto |
| Update | updateCompanySubscriptionPayment |
/v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId |
Auto |
| Delete | deleteCompanySubscriptionPayment |
/v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId |
Auto |
| Get | getCompanySubscriptionPayment |
/v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId |
Auto |
| List | listCompanySubscriptionPayments |
/v1/companysubscriptionpayments |
Auto |
Sys_paymentCustomer Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | none | - | Auto |
| Update | none | - | Auto |
| Delete | none | - | Auto |
| Get | getPaymentCustomerByUserId |
/v1/paymentcustomers/:userId |
Auto |
| List | listPaymentCustomers |
/v1/paymentcustomers |
Auto |
Sys_paymentMethod Default APIs
| Operation | API Name | Route | Explicitly Set |
|---|---|---|---|
| Create | none | - | Auto |
| Update | none | - | Auto |
| Delete | none | - | Auto |
| Get | none | - | Auto |
| List | listPaymentCustomerMethods |
/v1/paymentcustomermethods/:userId |
Auto |
When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.
API Reference
Create Companysubscription API
[Default create API] — This is the designated default create API for the companySubscription data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Initiates a new subscription purchase for the company. Creates the record in pending state and triggers the Stripe payment flow. The frontend receives a Stripe checkout URL. Once payment succeeds, the edgeFunctionPaymentDone callback automatically activates the subscription. Only tenantOwner/tenantAdmin can initiate. Prevents duplicate active/pending subscriptions.
API Frontend Description By The Backend Architect
Company admins use this to start their AI subscription. After calling this API, the response includes a Stripe checkout URL. Redirect the user to that URL to complete payment. Once payment succeeds, the subscription becomes active automatically. Do NOT let users set status or dates—those are system-managed.
Rest Route
The createCompanySubscription API REST controller can be triggered via the following route:
/v1/companysubscriptions
Rest Request Parameters
The createCompanySubscription api has got 9 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| activationDate | Date | true | request.body?.[“activationDate”] |
| expiryDate | Date | true | request.body?.[“expiryDate”] |
| status | Enum | true | request.body?.[“status”] |
| subscribedFeatures | String | false | request.body?.[“subscribedFeatures”] |
| lastRenewedBy | ID | false | request.body?.[“lastRenewedBy”] |
| currency | String | false | request.body?.[“currency”] |
| paymentStatusUpdatedAt | Date | false | request.body?.[“paymentStatusUpdatedAt”] |
| ownerId | ID | true | request.body?.[“ownerId”] |
| stripeSubscriptionId | String | false | request.body?.[“stripeSubscriptionId”] |
| activationDate : Start date/time when subscription is (re)activated. | |||
| expiryDate : Planned end date/time of subscription validity (inclusive). | |||
| status : Subscription status: active, inactive, pending, or expired. | |||
| subscribedFeatures : Array of enabled feature flags for this company’s subscription (e.g., aiAnalytics, reporting, notifications). | |||
| lastRenewedBy : ID of user (admin/mod) who last renewed or updated the subscription record; for audit. | |||
| currency : ISO currency code for the subscription payment. Defaults to usd. | |||
| paymentStatusUpdatedAt : Timestamp of the last payment status change from Stripe. | |||
| ownerId : The user who initiated the subscription purchase. Used for Stripe payment ownership. | |||
| stripeSubscriptionId : Stripe subscription ID for recurring billing management. Set after successful payment. |
REST Request To access the api you can use the REST controller with the path POST /v1/companysubscriptions
axios({
method: 'POST',
url: '/v1/companysubscriptions',
data: {
activationDate:"Date",
expiryDate:"Date",
status:"Enum",
subscribedFeatures:"String",
lastRenewedBy:"ID",
currency:"String",
paymentStatusUpdatedAt:"Date",
ownerId:"ID",
stripeSubscriptionId:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Companysubscription API
[Default update API] — This is the designated default update API for the companySubscription data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Admin-only API for manually adjusting subscription records. Only superAdmin/saasAdmin may use. Company admins cannot manually change their subscription—all status changes are driven by Stripe payment events. Used for platform support cases only.
API Frontend Description By The Backend Architect
Only visible to SaaS/SuperAdmin in support dashboards. Company admins have no access. Use for manual corrections only.
Rest Route
The updateCompanySubscription API REST controller can be triggered via the following route:
/v1/companysubscriptions/:companySubscriptionId
Rest Request Parameters
The updateCompanySubscription api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| activationDate | Date | false | request.body?.[“activationDate”] |
| expiryDate | Date | false | request.body?.[“expiryDate”] |
| status | Enum | false | request.body?.[“status”] |
| subscribedFeatures | String | false | request.body?.[“subscribedFeatures”] |
| lastRenewedBy | ID | false | request.body?.[“lastRenewedBy”] |
| paymentStatusUpdatedAt | Date | false | request.body?.[“paymentStatusUpdatedAt”] |
| stripeSubscriptionId | String | false | request.body?.[“stripeSubscriptionId”] |
| companySubscriptionId : This id paremeter is used to select the required data object that will be updated | |||
| activationDate : Start date/time when subscription is (re)activated. | |||
| expiryDate : Planned end date/time of subscription validity (inclusive). | |||
| status : Subscription status: active, inactive, pending, or expired. | |||
| subscribedFeatures : Array of enabled feature flags for this company’s subscription (e.g., aiAnalytics, reporting, notifications). | |||
| lastRenewedBy : ID of user (admin/mod) who last renewed or updated the subscription record; for audit. | |||
| paymentStatusUpdatedAt : Timestamp of the last payment status change from Stripe. | |||
| stripeSubscriptionId : Stripe subscription ID for recurring billing management. Set after successful payment. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/companysubscriptions/:companySubscriptionId
axios({
method: 'PATCH',
url: `/v1/companysubscriptions/${companySubscriptionId}`,
data: {
activationDate:"Date",
expiryDate:"Date",
status:"Enum",
subscribedFeatures:"String",
lastRenewedBy:"ID",
paymentStatusUpdatedAt:"Date",
stripeSubscriptionId:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companysubscription API
[Default get API] — This is the designated default get API for the companySubscription data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Retrieves the subscription details for the session’s company (tenantOwner/tenantAdmin/tenantUser); SaaS/SuperAdmin can fetch for any company via SaaS-level mode. Used for frontend subscription status checks and for feature gating by other services.
API Frontend Description By The Backend Architect
Used by company admins and by microservices/clients to inspect current subscription and its status/features. Access is allowed only to admins of own company unless SaaS/SuperAdmin.
Rest Route
The getCompanySubscription API REST controller can be triggered via the following route:
/v1/companysubscriptions/:companySubscriptionId
Rest Request Parameters
The getCompanySubscription api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| companySubscriptionId : 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/companysubscriptions/:companySubscriptionId
axios({
method: 'GET',
url: `/v1/companysubscriptions/${companySubscriptionId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Companysubscriptions API
[Default list API] — This is the designated default list API for the companySubscription data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Lists subscriptions. For admins, returns just their company’s; for superAdmin/saasAdmin, returns all companies. Useful for SaaS support dashboards or analytics.
API Frontend Description By The Backend Architect
Only visible to company admins or SaaS support/admins. Used to render support dashboards showing subscription status across companies or for monitoring purposes. Employees do not have access.
Rest Route
The listCompanySubscriptions API REST controller can be triggered via the following route:
/v1/companysubscriptions
Rest Request Parameters
Filter Parameters
The listCompanySubscriptions api supports 5 optional filter parameters for filtering list results:
activationDate (Date): Start date/time when subscription is (re)activated.
- Single date:
?activationDate=2024-01-15 - Multiple dates:
?activationDate=2024-01-15&activationDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?activationDate=null
expiryDate (Date): Planned end date/time of subscription validity (inclusive).
- Single date:
?expiryDate=2024-01-15 - Multiple dates:
?expiryDate=2024-01-15&expiryDate=2024-01-20 - Special:
$today,$ltoday,$week,$lweek,$month,$leq-<date>,$lin-<date> - Null:
?expiryDate=null
status (Enum): Subscription status: active, inactive, pending, or expired.
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
paymentStatus (Enum): Stripe payment status: pending (awaiting payment), paid (success), failed, canceled.
- Single:
?paymentStatus=<value>(case-insensitive) - Multiple:
?paymentStatus=<value1>&paymentStatus=<value2> - Null:
?paymentStatus=null
paymentConfirmation (Enum): An automatic property that is used to check the confirmed status of the payment set by webhooks.
- Single:
?paymentConfirmation=<value>(case-insensitive) - Multiple:
?paymentConfirmation=<value1>&paymentConfirmation=<value2> - Null:
?paymentConfirmation=null
REST Request To access the api you can use the REST controller with the path GET /v1/companysubscriptions
axios({
method: 'GET',
url: '/v1/companysubscriptions',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// activationDate: '<value>' // Filter by activationDate
// expiryDate: '<value>' // Filter by expiryDate
// status: '<value>' // Filter by status
// paymentStatus: '<value>' // Filter by paymentStatus
// paymentConfirmation: '<value>' // Filter by paymentConfirmation
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscriptions",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"companySubscriptions": [
{
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Delete Companysubscription API
[Default delete API] — This is the designated default delete API for the companySubscription data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Hard or soft deletes a company’s subscription record. Only superAdmin/saasAdmin may use. Should only be used for manual cleanup, not normal workflows (expired/inactive should be handled by update).
API Frontend Description By The Backend Architect
Visible only to SaaS/SuperAdmin for data cleanup. Not normally exposed in UI; used for extreme cases or accident cleanup. Company admins cannot delete; must mark as inactive/expired by update instead.
Rest Route
The deleteCompanySubscription API REST controller can be triggered via the following route:
/v1/companysubscriptions/:companySubscriptionId
Rest Request Parameters
The deleteCompanySubscription api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| companySubscriptionId : 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/companysubscriptions/:companySubscriptionId
axios({
method: 'DELETE',
url: `/v1/companysubscriptions/${companySubscriptionId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Cancel Companysubscription API
Cancels a company’s active subscription. Calls Stripe to cancel the subscription, then updates the local record to canceled status. Only tenantOwner/tenantAdmin of the owning company or superAdmin/saasAdmin can cancel.
API Frontend Description By The Backend Architect
Company admins use this to cancel their AI subscription. The Stripe subscription is canceled and the local record is updated. After cancellation, AI features are immediately blocked.
Rest Route
The cancelCompanySubscription API REST controller can be triggered via the following route:
/v1/cancelcompanysubscription/:companySubscriptionId
Rest Request Parameters
The cancelCompanySubscription api has got 8 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| activationDate | Date | false | request.body?.[“activationDate”] |
| expiryDate | Date | false | request.body?.[“expiryDate”] |
| status | Enum | false | request.body?.[“status”] |
| subscribedFeatures | String | false | request.body?.[“subscribedFeatures”] |
| lastRenewedBy | ID | false | request.body?.[“lastRenewedBy”] |
| paymentStatusUpdatedAt | Date | false | request.body?.[“paymentStatusUpdatedAt”] |
| stripeSubscriptionId | String | false | request.body?.[“stripeSubscriptionId”] |
| companySubscriptionId : This id paremeter is used to select the required data object that will be updated | |||
| activationDate : Start date/time when subscription is (re)activated. | |||
| expiryDate : Planned end date/time of subscription validity (inclusive). | |||
| status : Subscription status: active, inactive, pending, or expired. | |||
| subscribedFeatures : Array of enabled feature flags for this company’s subscription (e.g., aiAnalytics, reporting, notifications). | |||
| lastRenewedBy : ID of user (admin/mod) who last renewed or updated the subscription record; for audit. | |||
| paymentStatusUpdatedAt : Timestamp of the last payment status change from Stripe. | |||
| stripeSubscriptionId : Stripe subscription ID for recurring billing management. Set after successful payment. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/cancelcompanysubscription/:companySubscriptionId
axios({
method: 'PATCH',
url: `/v1/cancelcompanysubscription/${companySubscriptionId}`,
data: {
activationDate:"Date",
expiryDate:"Date",
status:"Enum",
subscribedFeatures:"String",
lastRenewedBy:"ID",
paymentStatusUpdatedAt:"Date",
stripeSubscriptionId:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companysubscriptionpayment API
This route is used to get the payment information by ID.
Rest Route
The getCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId
Rest Request Parameters
The getCompanySubscriptionPayment api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| sys_companySubscriptionPaymentId | ID | true | request.params?.[“sys_companySubscriptionPaymentId”] |
| sys_companySubscriptionPaymentId : 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/companysubscriptionpayment/:sys_companySubscriptionPaymentId
axios({
method: 'GET',
url: `/v1/companysubscriptionpayment/${sys_companySubscriptionPaymentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_companySubscriptionPayment": {
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Companysubscriptionpayments API
This route is used to list all payments.
Rest Route
The listCompanySubscriptionPayments API REST controller can be triggered via the following route:
/v1/companysubscriptionpayments
Rest Request Parameters
Filter Parameters
The listCompanySubscriptionPayments api supports 6 optional filter parameters for filtering list results:
ownerId (ID): An ID value to represent owner user who created the order
- Single:
?ownerId=<value> - Multiple:
?ownerId=<value1>&ownerId=<value2> - Null:
?ownerId=null
orderId (ID): an ID value to represent the orderId which is the ID parameter of the source companySubscription object
- Single:
?orderId=<value> - Multiple:
?orderId=<value1>&orderId=<value2> - Null:
?orderId=null
paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
- Single (partial match, case-insensitive):
?paymentId=<value> - Multiple:
?paymentId=<value1>&paymentId=<value2> - Null:
?paymentId=null
paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
- Single (partial match, case-insensitive):
?paymentStatus=<value> - Multiple:
?paymentStatus=<value1>&paymentStatus=<value2> - Null:
?paymentStatus=null
statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.
- Single (partial match, case-insensitive):
?statusLiteral=<value> - Multiple:
?statusLiteral=<value1>&statusLiteral=<value2> - Null:
?statusLiteral=null
redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.
- Single (partial match, case-insensitive):
?redirectUrl=<value> - Multiple:
?redirectUrl=<value1>&redirectUrl=<value2> - Null:
?redirectUrl=null
REST Request To access the api you can use the REST controller with the path GET /v1/companysubscriptionpayments
axios({
method: 'GET',
url: '/v1/companysubscriptionpayments',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// ownerId: '<value>' // Filter by ownerId
// orderId: '<value>' // Filter by orderId
// paymentId: '<value>' // Filter by paymentId
// paymentStatus: '<value>' // Filter by paymentStatus
// statusLiteral: '<value>' // Filter by statusLiteral
// redirectUrl: '<value>' // Filter by redirectUrl
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayments",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"sys_companySubscriptionPayments": [
{
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
Create Companysubscriptionpayment API
This route is used to create a new payment.
Rest Route
The createCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/companysubscriptionpayment
Rest Request Parameters
The createCompanySubscriptionPayment api has got 4 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| orderId | ID | true | request.body?.[“orderId”] |
| paymentId | String | true | request.body?.[“paymentId”] |
| paymentStatus | String | true | request.body?.[“paymentStatus”] |
| redirectUrl | String | false | request.body?.[“redirectUrl”] |
| orderId : an ID value to represent the orderId which is the ID parameter of the source companySubscription object | |||
| paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type | |||
| paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | |||
| redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. |
REST Request To access the api you can use the REST controller with the path POST /v1/companysubscriptionpayment
axios({
method: 'POST',
url: '/v1/companysubscriptionpayment',
data: {
orderId:"ID",
paymentId:"String",
paymentStatus:"String",
redirectUrl:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayment",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"sys_companySubscriptionPayment": {
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Update Companysubscriptionpayment API
This route is used to update an existing payment.
Rest Route
The updateCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId
Rest Request Parameters
The updateCompanySubscriptionPayment api has got 4 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| sys_companySubscriptionPaymentId | ID | true | request.params?.[“sys_companySubscriptionPaymentId”] |
| paymentId | String | false | request.body?.[“paymentId”] |
| paymentStatus | String | false | request.body?.[“paymentStatus”] |
| redirectUrl | String | false | request.body?.[“redirectUrl”] |
| sys_companySubscriptionPaymentId : This id paremeter is used to select the required data object that will be updated | |||
| paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type | |||
| paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment. | |||
| redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId
axios({
method: 'PATCH',
url: `/v1/companysubscriptionpayment/${sys_companySubscriptionPaymentId}`,
data: {
paymentId:"String",
paymentStatus:"String",
redirectUrl:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayment",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"sys_companySubscriptionPayment": {
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Delete Companysubscriptionpayment API
This route is used to delete a payment.
Rest Route
The deleteCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/companysubscriptionpayment/:sys_companySubscriptionPaymentId
Rest Request Parameters
The deleteCompanySubscriptionPayment api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| sys_companySubscriptionPaymentId | ID | true | request.params?.[“sys_companySubscriptionPaymentId”] |
| sys_companySubscriptionPaymentId : 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/companysubscriptionpayment/:sys_companySubscriptionPaymentId
axios({
method: 'DELETE',
url: `/v1/companysubscriptionpayment/${sys_companySubscriptionPaymentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayment",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"sys_companySubscriptionPayment": {
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companysubscriptionpaymentbyorderid API
This route is used to get the payment information by order id.
Rest Route
The getCompanySubscriptionPaymentByOrderId API REST controller can be triggered via the following route:
/v1/companySubscriptionpaymentbyorderid/:orderId
Rest Request Parameters
The getCompanySubscriptionPaymentByOrderId api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| orderId | ID | true | request.params?.[“orderId”] |
| orderId : an ID value to represent the orderId which is the ID parameter of the source companySubscription object. The parameter is used to query data. |
REST Request To access the api you can use the REST controller with the path GET /v1/companySubscriptionpaymentbyorderid/:orderId
axios({
method: 'GET',
url: `/v1/companySubscriptionpaymentbyorderid/${orderId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_companySubscriptionPayment": {
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Get Companysubscriptionpaymentbypaymentid API
This route is used to get the payment information by payment id.
Rest Route
The getCompanySubscriptionPaymentByPaymentId API REST controller can be triggered via the following route:
/v1/companySubscriptionpaymentbypaymentid/:paymentId
Rest Request Parameters
The getCompanySubscriptionPaymentByPaymentId api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| paymentId | String | true | request.params?.[“paymentId”] |
| paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data. |
REST Request To access the api you can use the REST controller with the path GET /v1/companySubscriptionpaymentbypaymentid/:paymentId
axios({
method: 'GET',
url: `/v1/companySubscriptionpaymentbypaymentid/${paymentId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_companySubscriptionPayment",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_companySubscriptionPayment": {
"id": "ID",
"ownerId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "String",
"statusLiteral": "String",
"redirectUrl": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
Start Companysubscriptionpayment API
Start payment for companySubscription
Rest Route
The startCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/startcompanysubscriptionpayment/:companySubscriptionId
Rest Request Parameters
The startCompanySubscriptionPayment api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| paymentUserParams | Object | true | request.body?.[“paymentUserParams”] |
| companySubscriptionId : This id paremeter is used to select the required data object that will be updated | |||
| paymentUserParams : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/startcompanysubscriptionpayment/:companySubscriptionId
axios({
method: 'PATCH',
url: `/v1/startcompanysubscriptionpayment/${companySubscriptionId}`,
data: {
paymentUserParams:"Object",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
"paymentResult": {
"paymentTicketId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "Enum",
"paymentIntentInfo": "Object",
"statusLiteral": "String",
"amount": "Double",
"currency": "String",
"success": true,
"description": "String",
"metadata": "Object",
"paymentUserParams": "Object"
}
}
Refresh Companysubscriptionpayment API
Refresh payment info for companySubscription from Stripe
Rest Route
The refreshCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/refreshcompanysubscriptionpayment/:companySubscriptionId
Rest Request Parameters
The refreshCompanySubscriptionPayment api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| paymentUserParams | Object | false | request.body?.[“paymentUserParams”] |
| companySubscriptionId : This id paremeter is used to select the required data object that will be updated | |||
| paymentUserParams : The user parameters that should be defined to refresh a stripe payment process |
REST Request To access the api you can use the REST controller with the path PATCH /v1/refreshcompanysubscriptionpayment/:companySubscriptionId
axios({
method: 'PATCH',
url: `/v1/refreshcompanysubscriptionpayment/${companySubscriptionId}`,
data: {
paymentUserParams:"Object",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
"paymentResult": {
"paymentTicketId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "Enum",
"paymentIntentInfo": "Object",
"statusLiteral": "String",
"amount": "Double",
"currency": "String",
"success": true,
"description": "String",
"metadata": "Object",
"paymentUserParams": "Object"
}
}
Callback Companysubscriptionpayment API
Refresh payment values by gateway webhook call for companySubscription
Rest Route
The callbackCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/callbackcompanysubscriptionpayment
Rest Request Parameters
The callbackCompanySubscriptionPayment api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | false | request.body?.[“companySubscriptionId”] |
| companyId | String | false | request.body?.[“companyId”] |
| companySubscriptionId : The order id parameter that will be read from webhook callback params | |||
| companyId : The companyId parameter that will be read from webhook callback params metadata |
REST Request To access the api you can use the REST controller with the path POST /v1/callbackcompanysubscriptionpayment
axios({
method: 'POST',
url: '/v1/callbackcompanysubscriptionpayment',
data: {
companySubscriptionId:"ID",
companyId:"String",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "POST",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
"paymentResult": {
"paymentTicketId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "Enum",
"paymentIntentInfo": "Object",
"statusLiteral": "String",
"amount": "Double",
"currency": "String",
"success": true,
"description": "String",
"metadata": "Object",
"paymentUserParams": "Object"
}
}
Get Paymentcustomerbyuserid API
This route is used to get the payment customer information by user id.
Rest Route
The getPaymentCustomerByUserId API REST controller can be triggered via the following route:
/v1/paymentcustomers/:userId
Rest Request Parameters
The getPaymentCustomerByUserId api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| userId | ID | true | request.params?.[“userId”] |
| userId : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data. |
REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers/:userId
axios({
method: 'GET',
url: `/v1/paymentcustomers/${userId}`,
data: {
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_paymentCustomer",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"sys_paymentCustomer": {
"id": "ID",
"userId": "ID",
"customerId": "String",
"platform": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
List Paymentcustomers API
This route is used to list all payment customers.
Rest Route
The listPaymentCustomers API REST controller can be triggered via the following route:
/v1/paymentcustomers
Rest Request Parameters
Filter Parameters
The listPaymentCustomers api supports 3 optional filter parameters for filtering list results:
userId (ID): An ID value to represent the user who is created as a stripe customer
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
- Single (partial match, case-insensitive):
?customerId=<value> - Multiple:
?customerId=<value1>&customerId=<value2> - Null:
?customerId=null
platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
- Single (partial match, case-insensitive):
?platform=<value> - Multiple:
?platform=<value1>&platform=<value2> - Null:
?platform=null
REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomers
axios({
method: 'GET',
url: '/v1/paymentcustomers',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '<value>' // Filter by userId
// customerId: '<value>' // Filter by customerId
// platform: '<value>' // Filter by platform
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_paymentCustomers",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"sys_paymentCustomers": [
{
"id": "ID",
"userId": "ID",
"customerId": "String",
"platform": "String",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
List Paymentcustomermethods API
This route is used to list all payment customer methods.
Rest Route
The listPaymentCustomerMethods API REST controller can be triggered via the following route:
/v1/paymentcustomermethods/:userId
Rest Request Parameters
The listPaymentCustomerMethods api has got 1 regular request parameter
| Parameter | Type | Required | Population |
|---|---|---|---|
| userId | ID | true | request.params?.[“userId”] |
| userId : An ID value to represent the user who owns the payment method. The parameter is used to query data. |
Filter Parameters
The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results:
paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.
- Single (partial match, case-insensitive):
?paymentMethodId=<value> - Multiple:
?paymentMethodId=<value1>&paymentMethodId=<value2> - Null:
?paymentMethodId=null
customerId (String): A string value to represent the customer id which is generated on the payment gateway.
- Single (partial match, case-insensitive):
?customerId=<value> - Multiple:
?customerId=<value1>&customerId=<value2> - Null:
?customerId=null
cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.
- Single (partial match, case-insensitive):
?cardHolderName=<value> - Multiple:
?cardHolderName=<value1>&cardHolderName=<value2> - Null:
?cardHolderName=null
cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
- Single (partial match, case-insensitive):
?cardHolderZip=<value> - Multiple:
?cardHolderZip=<value1>&cardHolderZip=<value2> - Null:
?cardHolderZip=null
platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
- Single (partial match, case-insensitive):
?platform=<value> - Multiple:
?platform=<value1>&platform=<value2> - Null:
?platform=null
cardInfo (Object): A Json value to store the card details of the payment method.
- Single:
?cardInfo=<value> - Multiple:
?cardInfo=<value1>&cardInfo=<value2> - Null:
?cardInfo=null
REST Request To access the api you can use the REST controller with the path GET /v1/paymentcustomermethods/:userId
axios({
method: 'GET',
url: `/v1/paymentcustomermethods/${userId}`,
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// paymentMethodId: '<value>' // Filter by paymentMethodId
// customerId: '<value>' // Filter by customerId
// cardHolderName: '<value>' // Filter by cardHolderName
// cardHolderZip: '<value>' // Filter by cardHolderZip
// platform: '<value>' // Filter by platform
// cardInfo: '<value>' // Filter by cardInfo
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "sys_paymentMethods",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"sys_paymentMethods": [
{
"id": "ID",
"paymentMethodId": "String",
"userId": "ID",
"customerId": "String",
"cardHolderName": "String",
"cardHolderZip": "String",
"platform": "String",
"cardInfo": "Object",
"companyId": "ID",
"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.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 16 - SubscriptionManagement Service CompanySubscription Payment Flow
This document is a part of a REST API guide for the workforceos project. It is designed for AI agents that will generate frontend code to consume the project’s backend.
Stripe Payment Flow For CompanySubscription
CompanySubscription is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database.
The ID of this data object—referenced as companySubscriptionId in the general business logic—will be used as the orderId in the payment flow.
Accessing the service API for the payment flow API
The Workforceos application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders.
To access the related APIs, use the base URL of the subscriptionManagement service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment.
For the subscriptionManagement service, the base URLs are:
- Preview:
https://workforceos.prw.mindbricks.com/subscriptionmanagement-api - Staging:
https://workforceos-stage.mindbricks.co/subscriptionmanagement-api - Production:
https://workforceos.mindbricks.co/subscriptionmanagement-api
Creating the CompanySubscription
While creating the companySubscription instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of companySubscription). The payment flow begins after the object is created.
Because of the data object’s Stripe order settings, the payment flow is aware of the following fields, references, and their purposes:
-
id(used asorderIdor${dataObject.objectName}Id): The unique identifier of the data object instance at the center of the payment flow. -
orderIdProperty: The order identifier is read from theidproperty of the data object. -
amountProperty: The payment amount is read from theamountproperty of the data object. -
currency: The payment currency is statically set tousd. -
description: The payment description is resolved fromrunMScript(() => ('WorkforceOS AI Analytics Subscription for company ' + this.companyId), {"path":"services[9].dataObjects[0].objectSettings.stripeOrder.configuration.description"}). -
orderStatusProperty:paymentStatusis updated automatically by the payment flow using a mapped status value. -
orderStatusUpdateDateProperty:paymentStatusUpdatedAtstores the timestamp of the latest payment status update. -
orderOwnerIdProperty:ownerIdis used by the payment flow to verify the order owner and match it with the current user’s ID. -
mapPaymentResultToOrderStatus: The order status is written to the data object instance using the following mapping.
paymentResultStarted:runMScript(() => ('pending'), {"path":"services[9].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultStarted"})
paymentResultCanceled:runMScript(() => ('canceled'), {"path":"services[9].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultCanceled"})
paymentResultFailed:runMScript(() => ('failed'), {"path":"services[9].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultFailed"})
paymentResultSuccess:runMScript(() => ('paid'), {"path":"services[9].dataObjects[0].objectSettings.stripeOrder.configuration.mapPaymentResultToOrderStatus.paymentResultSuccess"})
Before Payment Flow Starts
It is assumed that the frontend provides a “Pay” or “Checkout” button that initiates the payment flow. The following steps occur after the user clicks this button.
Note that an companySubscription instance must already exist to represent the order being paid, with its initial status set.
A Stripe payment flow can be implemented in several ways, but the best practice is to use a PaymentIntent and manage it jointly from the backend and frontend.
A PaymentIntent represents the intent to collect payment for a given order (or any payable entity).
In the Workforceos application, the PaymentIntent is created in the backend, while the PaymentMethod (the user’s stored card information) is created in the frontend.
Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference.
The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to add or remove payment methods.
The user must select a Payment Method before starting the payment flow.
Listing the Payment Methods for the User
To list the payment methods of the currently logged-in user, call the following system API (unversioned):
GET /payment-methods/list
This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope.
const response = await fetch("$serviceUrl/payment-methods/list", {
method: "GET",
headers: { "Content-Type": "application/json" },
});
Example response:
[
{
"id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01",
"paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8",
"userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
"customerId": "cus_TNgWUw5QkmUPLa",
"cardHolderName": "John Doe",
"cardHolderZip": "34662",
"platform": "stripe",
"cardInfo": {
"brand": "visa",
"last4": "4242",
"checks": {
"cvc_check": "pass",
"address_postal_code_check": "pass"
},
"funding": "credit",
"exp_month": 11,
"exp_year": 2033
},
"isActive": true,
"createdAt": "2025-11-07T19:16:38.469Z",
"updatedAt": "2025-11-07T19:16:38.469Z",
"_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2"
}
]
In each payment method object, the following fields are useful for displaying to the user:
for (const method of paymentMethods) {
const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons
const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow
const cardHolderName = method.cardHolderName; // show in list
const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number
const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date
const id = method.id; // internal DB record ID, used for deletion
const customerId = method.customerId; // Stripe customer reference
}
If the list is empty, prompt the user to add a new payment method.
Creating a Payment Method
The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled entirely through Stripe.js on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse.
Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns.
To initialize Stripe on the frontend, include your public key:
<script src="https://js.stripe.com/v3/?advancedFraudSignals=false"></script>
const stripe = Stripe("pk_test_51POkqt4..................");
const elements = stripe.elements();
const cardNumberElement = elements.create("cardNumber", {
style: { base: { color: "#545454", fontSize: "16px" } },
});
cardNumberElement.mount("#card-number-element");
const cardExpiryElement = elements.create("cardExpiry", {
style: { base: { color: "#545454", fontSize: "16px" } },
});
cardExpiryElement.mount("#card-expiry-element");
const cardCvcElement = elements.create("cardCvc", {
style: { base: { color: "#545454", fontSize: "16px" } },
});
cardCvcElement.mount("#card-cvc-element");
// Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure).
You can dynamically show the card brand while typing:
cardNumberElement.on("change", (event) => {
const cardBrand = event.brand;
const cardNumberDiv = document.getElementById("card-number-element");
cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand);
});
Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code.
const { paymentMethod, error } = await stripe.createPaymentMethod({
type: "card",
card: cardNumberElement,
billing_details: {
name: cardholderName.value,
address: { postal_code: cardholderZip.value },
},
});
When a paymentMethod is successfully created, send its ID to your backend to attach it to the logged-in user’s account.
Use the system API (unversioned):
POST /payment-methods/add
Example:
const response = await fetch("$serviceUrl/payment-methods/add", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ paymentMethodId: paymentMethod.id }),
});
When addPaymentMethod is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use.
Example response:
{
"isActive": true,
"cardHolderName": "John Doe",
"userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
"customerId": "cus_TNgWUw5QkmUPLa",
"paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
"platform": "stripe",
"cardHolderZip": "34662",
"cardInfo": {
"brand": "visa",
"last4": "4242",
"funding": "credit",
"exp_month": 11,
"exp_year": 2033
},
"id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf",
"createdAt": "2025-11-07T20:16:55.451Z",
"updatedAt": "2025-11-07T20:16:55.451Z"
}
You can append this new entry directly to the UI list or refresh the list using the listPaymentMethods API.
Deleting a Payment Method
To remove a saved payment method from the current user’s account, call the system API (unversioned):
DELETE /payment-methods/delete/:paymentMethodId
Example:
await fetch(
`$serviceUrl/payment-methods/delete/${paymentMethodId}`,
{
method: "DELETE",
headers: { "Content-Type": "application/json" },
}
);
Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object
The payment flow is initiated in the backend through the startCompanySubscriptionPayment API.
This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend forces the user to select a payment method before initiating the payment.
The startCompanySubscriptionPayment API is a versioned Business Logic API and follows the same structure as other business APIs.
In the Workforceos application, the payment flow starts by creating a Stripe PaymentIntent and confirming it in a single step within the backend.
In a typical (“happy”) path, when the startCompanySubscriptionPayment API is called, the response will include a successful or failed PaymentIntent result inside the paymentResult object, along with the companySubscription object.
However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately.
In such cases, control should return to a frontend page to allow the user to finish the process.
To enable this, a return_url must be provided during the PaymentIntent creation step.
Although technically optional, it is strongly recommended to include a return_url.
This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction.
The return_url must be a frontend URL.
The paymentUserParams parameter of the startCompanySubscriptionPayment API contains the data necessary to create the Stripe PaymentIntent.
Call the API as follows:
const response = await fetch(
`$serviceUrl/v1/startcompanySubscriptionpayment/${orderId}`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
paymentUserParams: {
paymentMethodId,
return_url: `${yourFrontendReturnUrl}`,
},
}),
}
);
The API response will contain a paymentResult object.
If an error occurs, it will begin with { "result": "ERR" }.
Otherwise, it will include the PaymentIntent information:
{
"paymentResult": {
"success": true,
"paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da",
"orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
"paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
"paymentStatus": "succeeded",
"paymentIntentInfo": {
"paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
"clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg",
"publicKey": "pk_test_51POkqWP5uU",
"status": "succeeded"
},
"statusLiteral": "success",
"amount": 10,
"currency": "USD",
"description": "Your credit card is charged for babilOrder for 10",
"metadata": {
"order": "Purchase-Purchase-order",
"orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
"checkoutName": "babilOrder"
},
"paymentUserParams": {
"paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
"return_url": "${yourFrontendReturnUrl}"
}
}
}
Start Companysubscriptionpayment API
Start payment for companySubscription
Rest Route
The startCompanySubscriptionPayment API REST controller can be triggered via the following route:
/v1/startcompanysubscriptionpayment/:companySubscriptionId
Rest Request Parameters
The startCompanySubscriptionPayment api has got 2 regular request parameters
| Parameter | Type | Required | Population |
|---|---|---|---|
| companySubscriptionId | ID | true | request.params?.[“companySubscriptionId”] |
| paymentUserParams | Object | true | request.body?.[“paymentUserParams”] |
| companySubscriptionId : This id paremeter is used to select the required data object that will be updated | |||
| paymentUserParams : The user parameters that should be defined to start a stripe payment process. Must include paymentMethodId. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/startcompanysubscriptionpayment/:companySubscriptionId
axios({
method: 'PATCH',
url: `/v1/startcompanysubscriptionpayment/${companySubscriptionId}`,
data: {
paymentUserParams:"Object",
},
params: {
}
});
REST Response
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companySubscription",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"companySubscription": {
"id": "ID",
"activationDate": "Date",
"expiryDate": "Date",
"status": "Enum",
"status_idx": "Integer",
"subscribedFeatures": "String",
"lastRenewedBy": "ID",
"currency": "String",
"paymentStatus": "Enum",
"paymentStatus_idx": "Integer",
"paymentStatusUpdatedAt": "Date",
"ownerId": "ID",
"stripeSubscriptionId": "String",
"amount": "Integer",
"companyId": "ID",
"paymentConfirmation": "Enum",
"paymentConfirmation_idx": "Integer",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
"paymentResult": {
"paymentTicketId": "ID",
"orderId": "ID",
"paymentId": "String",
"paymentStatus": "Enum",
"paymentIntentInfo": "Object",
"statusLiteral": "String",
"amount": "Double",
"currency": "String",
"success": true,
"description": "String",
"metadata": "Object",
"paymentUserParams": "Object"
}
}
Analyzing the API Response
After calling the startCompanySubscriptionPayment API, the most common expected outcome is a confirmed and completed payment.
However, several alternate cases should be handled on the frontend.
System Error Case
The API may return a classic service-level error (unrelated to payment).
Check the HTTP status code of the response. It should be 200 or 201.
Any 400, 401, 403, or 404 indicates a system error.
{
"result": "ERR",
"status": 404,
"message": "Record not found",
"date": "2025-11-08T00:57:54.820Z"
}
Handle system errors on the payment page (show a retry option). Do not navigate to the result page.
Payment Error Case
The API performs both database operations and the Stripe payment operation.
If the payment fails but the service logic succeeds, the API may still return a 200 OK status, with the failure recorded in the paymentResult.
In this case, show an error message and allow the user to retry.
{
"status": "OK",
"statusCode": "200",
"companySubscription": {
"id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
"status": "failed"
},
"paymentResult": {
"result": "ERR",
"status": 500,
"message": "Stripe error message: Your card number is incorrect.",
"errCode": "invalid_number",
"date": "2025-11-08T00:57:54.820Z"
}
}
Payment errors should be handled on the payment page (retry option). Do not go to the result page.
Happy Case
When both the service and payment result succeed, this is considered the happy path.
In this case, use the companySubscription and paymentResult objects in the response to display a success message to the user.
amount and description values are included to help you show payment details on the result page.
{
"status": "OK",
"statusCode": "200",
"order": {
"id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
"status": "paid"
},
"paymentResult": {
"success": true,
"paymentStatus": "succeeded",
"paymentIntentInfo": {
"status": "succeeded"
},
"amount": 10,
"currency": "USD",
"description": "Your credit card is charged for babilOrder for 10"
}
}
To verify success:
if (paymentResult.paymentIntentInfo.status === "succeeded") {
// Redirect to result page
}
Note: A successful result does not trigger fulfillment immediately. Fulfillment begins only after the Stripe webhook updates the database. It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page.
Handle the happy case in the result page by sending the companySubscriptionId and the payment intent secret.
const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);
Edge Cases
Although startCompanySubscriptionPayment is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required.
You must handle these cases in both the payment page and the result page, because some next actions are available immediately, while others occur only after a redirect.
If the paymentIntentInfo.status equals "requires_action", handle it using Stripe.js as shown below:
if (paymentResult.paymentIntentInfo.status === "requires_action") {
await runNextAction(
paymentResult.paymentIntentInfo.clientSecret,
paymentResult.paymentIntentInfo.publicKey
);
}
Helper function:
async function runNextAction(clientSecret, publicKey) {
const stripe = Stripe(publicKey);
const { error } = await stripe.handleNextAction({ clientSecret });
if (error) {
console.log("next_action error:", error);
showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500");
throw new Error(error.message);
}
}
After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page.
const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);
if (paymentIntent.status === "succeeded") {
showToast("Payment successful!", "fa-circle-check text-green-500");
} else if (paymentIntent.status === "processing") {
showToast("Payment is processing…", "fa-circle-info text-blue-500");
} else if (paymentIntent.status === "requires_payment_method") {
showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500");
}
const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);
The Result Page
The payment result page should handle the following steps:
- Read
orderIdandpayment_intent_client_secretfrom the query parameters. - Retrieve the PaymentIntent from Stripe and check its status.
- If required, handle any
next_actionand re-fetch the PaymentIntent. - If the status is
"succeeded", display a clear visual confirmation. - Fetch the
companySubscriptioninstance from the backend to display any additional order or fulfillment details.
Note that paymentIntent status only gives information about the Stripe side.
The companySubscription instance in the service should also ve updated to start the fulfillment.
In most cases, the startcompanySubscriptionPayment api updates the status of the order using the response of the paymentIntent confirmation,
but as stated above in some cases this update can be done only when the webhook executes.
So in teh result page always get the final payment status in the `companySubscription.
To ensure that service i
To fetch the companySubscription instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the companySubscription instance.
if (companySubscription.paymentConfirmation == "canceled") {
// the payment is canceled, user can be informed that they should try again
} if (companySubscription.paymentConfirmation == "paid") {
// service knows that payment is done, user can be informed that fullfillment started
} else {
// it may be pending, processing
// Fetch the object again until a canceled or paid status
}
Payment Flow via MCP (AI Chat Integration)
The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The subscriptionManagement service exposes an initiatePayment MCP tool that the AI can call when the user wants to pay for an order.
How initiatePayment Works in MCP
- User asks to pay — e.g., “I want to pay for my order”
- AI calls
initiatePaymentMCP tool withorderId(andorderTypeif multiple order types exist) - Tool validates the order exists, is payable, and the user is authorized
- Tool returns
__frontendActionwithtype: "payment"— this is NOT a direct payment execution - Frontend chat UI renders a
PaymentActionCardwith a “Pay Now” button - User clicks “Pay Now” — the frontend opens a payment modal with
CheckoutForm - Standard Stripe flow proceeds (payment method selection, 3DS handling, etc.)
Frontend Action Response Format
The initiatePayment MCP tool returns:
{
"__frontendAction": {
"type": "payment",
"orderId": "uuid",
"orderType": "companySubscription",
"serviceName": "subscriptionManagement",
"amount": 99.99,
"currency": "USD",
"description": "Order description"
},
"message": "Payment is ready. Click the button below to proceed."
}
MCP Client Architecture
The frontend communicates with MCP tools through the MCP BFF (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides:
- SSE Streaming: Chat messages stream via
/api/chat/streamwith event types:start,text,tool_start,tool_executing,tool_result,error,done - Tool Result Extraction: The frontend’s
MessageBubblecomponent inspects tool results for__frontendActionfields - Action Dispatch: The
ActionCardcomponent dispatches to type-specific cards (e.g.,PaymentActionCardfortype: "payment")
The PaymentActionCard component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface.
WORKFORCEOS
FRONTEND GUIDE FOR AI CODING AGENTS - PART 17 - AgentHub Service
This document is a part of a REST API guide for the workforceos 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://workforceos.prw.mindbricks.com/agenthub-api - Staging:
https://workforceos-stage.mindbricks.co/agenthub-api - Production:
https://workforceos.mindbricks.co/agenthub-api
Tenant URL Prefix and Header Forwarding
Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix
/{tenantCodename}(example:/babil/products) - production: tenant subdomain (example:
babil.appname...)
Then backend API calls must always claim target tenant with header:
headers["mbx-company-codename"] = tenantCodenameFromUrl;
URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to agentHub service.
Scope
AgentHub Service Description
AI Agent Hub
AgentHub service provides apis and business logic for following data objects in workforceos 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:
{
"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.
{
"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.
AI Agents
This service exposes 2 AI agents as dedicated API endpoints. Each agent is a backend-managed AI pipeline with its own model, system prompt, and optional tool access. The frontend interacts with agents through standard HTTP requests — either synchronous REST calls or streaming SSE connections.
Agent Overview
| Agent | Modality | Mode | REST | SSE | Auth | Path |
|---|---|---|---|---|---|---|
workforceAssistant |
text | chat | Yes | No | Yes | /agents/workforceAssistant |
workforceInsightGenerator |
text | task | Yes | Yes | Yes | /agents/workforceInsightGenerator |
Agent: workforceAssistant
AI assistant for workforce management providing data insights and management advice
- Modality:
text— text-in, text-out - Execution Mode:
chat— multi-turn conversation with history management - Provider / Model:
openai/gpt-4o - Response Format:
text - Token Budget: 2000
- Timeout: 30ms
REST Endpoint (Synchronous)
POST {baseUrl}/agents/workforceAssistant
Authorization: Bearer {accessToken}
Content-Type: application/json
Request Body:
{
"conversationId": "optional-uuid-for-history",
"prompt": "Your message or instruction to the agent"
}
Response:
{
"success": true,
"data": {
"response": "Agent response text",
"conversationId": "uuid"
}
}
Conversation Management
This agent operates in chat mode with conversation history. To maintain context across messages:
- On the first message, omit
conversationId— the response will include a new one. - On subsequent messages, pass the same
conversationIdto continue the conversation. - Each conversation stores up to 100 messages in memory.
Agent: workforceInsightGenerator
AI agent that generates workforce analytics insights using actual company data from APIs
- Modality:
text— text-in, text-out - Execution Mode:
task— single request/response (one-shot) - Provider / Model:
openai/gpt-4o - Response Format:
json - Timeout: 120000ms
REST Endpoint (Synchronous)
POST {baseUrl}/agents/workforceInsightGenerator
Authorization: Bearer {accessToken}
Content-Type: application/json
Request Body:
{
"prompt": "Your message or instruction to the agent"
}
Response:
{
"success": true,
"data": {
"response": "Agent response text"
}
}
SSE Endpoint (Streaming)
POST {baseUrl}/agents/workforceInsightGenerator/stream
Authorization: Bearer {accessToken}
Content-Type: application/json
The request body is the same as the REST endpoint. The response is a Server-Sent Events stream:
event: chunk
data: {"content":"partial response text..."}
event: chunk
data: {"content":"more text..."}
event: complete
data: {}
Frontend integration pattern:
const response = await fetch(`${baseUrl}/agents/workforceInsightGenerator/stream`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'mbx-company-codename': tenantCodename,
},
body: JSON.stringify({ prompt: userMessage }),
});
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 lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6));
if (data.content) {
// Append data.content to UI (streaming text)
}
}
}
}
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
axios({
method: 'GET',
url: `/v1/agentoverride/${sys_agentOverrideId}`,
data: {
},
params: {
}
});
REST Response
{
"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
axios({
method: 'GET',
url: '/v1/agentoverrides',
data: {
},
params: {
}
});
REST Response
{
"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 9 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”] | |
| 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 }. |
REST Request To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId
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",
},
params: {
}
});
REST Response
{
"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
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
{
"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
axios({
method: 'DELETE',
url: `/v1/agentoverride/${sys_agentOverrideId}`,
data: {
},
params: {
}
});
REST Response
{
"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=<value> - Multiple:
?serviceName=<value1>&serviceName=<value2> - Null:
?serviceName=null
REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalog
axios({
method: 'GET',
url: '/v1/toolcatalog',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// serviceName: '<value>' // Filter by serviceName
}
});
REST Response
{
"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
axios({
method: 'GET',
url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
data: {
},
params: {
}
});
REST Response
{
"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=<value> - Multiple:
?agentName=<value1>&agentName=<value2> - Null:
?agentName=null
agentType (Enum): Whether this was a design-time or dynamic agent.
- Single:
?agentType=<value>(case-insensitive) - Multiple:
?agentType=<value1>&agentType=<value2> - Null:
?agentType=null
source (Enum): How the agent was triggered.
- Single:
?source=<value>(case-insensitive) - Multiple:
?source=<value1>&source=<value2> - Null:
?source=null
userId (ID): User who triggered the execution.
- Single:
?userId=<value> - Multiple:
?userId=<value1>&userId=<value2> - Null:
?userId=null
status (Enum): Execution status.
- Single:
?status=<value>(case-insensitive) - Multiple:
?status=<value1>&status=<value2> - Null:
?status=null
REST Request To access the api you can use the REST controller with the path GET /v1/agentexecutions
axios({
method: 'GET',
url: '/v1/agentexecutions',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// agentName: '<value>' // Filter by agentName
// agentType: '<value>' // Filter by agentType
// source: '<value>' // Filter by source
// userId: '<value>' // Filter by userId
// status: '<value>' // Filter by status
}
});
REST Response
{
"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
axios({
method: 'GET',
url: `/v1/agentexecution/${sys_agentExecutionId}`,
data: {
},
params: {
}
});
REST Response
{
"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 - Documentation overview and index
- llms-restapi.txt - Complete REST API reference
- llms-full.txt - Complete documentation
Generated by Mindbricks Genesis Engine