# Workforce Operating System - REST API Reference
> Complete REST API documentation for all services in Workforce Operating System
This document provides comprehensive REST API documentation for all services. Use this reference to understand available endpoints, request/response formats, and authentication requirements.
---
## Table of Contents
- [Introduction](#introduction)
- [Auth Service REST API](#auth-service-rest-api-guide)
- [EmployeeProfile Service REST API](#employeeprofile-service-rest-api-guide)
- [ScheduleManagement Service REST API](#schedulemanagement-service-rest-api-guide)
- [AttendanceManagement Service REST API](#attendancemanagement-service-rest-api-guide)
- [TaskManagement Service REST API](#taskmanagement-service-rest-api-guide)
- [LeaveManagement Service REST API](#leavemanagement-service-rest-api-guide)
- [PayrollReporting Service REST API](#payrollreporting-service-rest-api-guide)
- [AnnouncementManagement Service REST API](#announcementmanagement-service-rest-api-guide)
- [AiWorkforceAnalytics Service REST API](#aiworkforceanalytics-service-rest-api-guide)
- [SubscriptionManagement Service REST API](#subscriptionmanagement-service-rest-api-guide)
- [AgentHub Service REST API](#agenthub-service-rest-api-guide)
- [Bff Service REST API](#bff-service-rest-api-guide)
- [Notification Service REST API](#notification-service-rest-api-guide)
---
## Introduction
# 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](/document/docs/auth-service/rest-api-guide.html)
* **Event Guide** – helpful for event-driven or cross-service integrations
[Auth Event Guide](/document/docs/auth-service/event-guide.html)
* **Service Design Document** – overall structure, patterns, and logic
[Auth Service Design](/document/docs/auth-service/service-design.html)
> **Note:** For most frontend use cases, the **REST API Guide** will be the primary source. The **Event Guide** and **Service Design** documents are especially useful when integrating with other backend microservices or building systems that interact with the auth service indirectly.
## Using the BFF (Backend-for-Frontend) Service
In Mindbricks, all backend services are designed with an advanced **CQRS (Command Query Responsibility Segregation)** architecture. Within this architecture, **business services** are responsible for managing their respective domains and ensuring the accuracy and freshness of domain data.
The **BFF service** complements these business services by providing a **read-only** aggregation and query layer tailored specifically for frontend and client-side applications.
### Key Principles of the BFF Service
* **Elasticsearch Replicas for Fast Queries:**
Each data object managed by a business service is automatically replicated as an **Elasticsearch index**, making it accessible for fast, frontend-oriented queries through the BFF.
* **Cross-Service Data Aggregation:**
The BFF offers an **aggregation layer** capable of combining data across multiple services, enabling complex filters, searches, and unified views of related data.
* **Read-Only by Design:**
The BFF service is **strictly read-only**. All create, update, or delete operations must be performed through the relevant business services, or via event-driven sagas if designed.
### BFF Service Documentation
* **REST API Guide** – querying aggregated and indexed data
[BFF REST API Guide](/document/docs/bff-service/rest-api-guide.html)
* **Event Guide** – syncing strategies across replicas
[BFF Event Guide](/document/docs/bff-service/event-guide.html)
* **Service Design** – aggregation patterns and index structures
[BFF Service Design](/document/docs/bff-service/service-design.html)
> **Tip:** Use the BFF service as the **main entry point for all frontend data queries**. It simplifies access, reduces round-trips, and ensures that data is shaped appropriately for the UI layer.
## Business Services Overview
The `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](#using-the-bff-backend-for-frontend-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:**
* [REST API Guide](/document/docs/employeeProfile-service/rest-api-guide.html)
* [Event Guide](/document/docs/employeeProfile-service/event-guide.html)
* [Service Design](/document/docs/employeeProfile-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/scheduleManagement-service/rest-api-guide.html)
* [Event Guide](/document/docs/scheduleManagement-service/event-guide.html)
* [Service Design](/document/docs/scheduleManagement-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/attendanceManagement-service/rest-api-guide.html)
* [Event Guide](/document/docs/attendanceManagement-service/event-guide.html)
* [Service Design](/document/docs/attendanceManagement-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/taskManagement-service/rest-api-guide.html)
* [Event Guide](/document/docs/taskManagement-service/event-guide.html)
* [Service Design](/document/docs/taskManagement-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/leaveManagement-service/rest-api-guide.html)
* [Event Guide](/document/docs/leaveManagement-service/event-guide.html)
* [Service Design](/document/docs/leaveManagement-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/payrollReporting-service/rest-api-guide.html)
* [Event Guide](/document/docs/payrollReporting-service/event-guide.html)
* [Service Design](/document/docs/payrollReporting-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/announcementManagement-service/rest-api-guide.html)
* [Event Guide](/document/docs/announcementManagement-service/event-guide.html)
* [Service Design](/document/docs/announcementManagement-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/aiWorkforceAnalytics-service/rest-api-guide.html)
* [Event Guide](/document/docs/aiWorkforceAnalytics-service/event-guide.html)
* [Service Design](/document/docs/aiWorkforceAnalytics-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/subscriptionManagement-service/rest-api-guide.html)
* [Event Guide](/document/docs/subscriptionManagement-service/event-guide.html)
* [Service Design](/document/docs/subscriptionManagement-service/service-design.html)
**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:**
* [REST API Guide](/document/docs/agentHub-service/rest-api-guide.html)
* [Event Guide](/document/docs/agentHub-service/event-guide.html)
* [Service Design](/document/docs/agentHub-service/service-design.html)
**Base URL Examples:**
| Environment | URL |
|-------------|---------------------|
| **Preview** | `https://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_here`
API keys are long-lived and don't expire like JWT tokens. Create one from the profile page.
- **JWT Token:** `Authorization: Bearer {accessToken}`
Use a valid access token obtained from the login API.
> **OAuth is not supported** for MCP connections at this time.
### Connecting from Cursor
Add the following to your project's `.cursor/mcp.json`:
```json
{
"mcpServers": {
"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`):
```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.
---
## Service API Documentation
# REST API GUIDE
## workforceos-auth-service
**Version:** `1.0.20`
Authentication service for the project
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the Auth Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our Auth Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the Auth Service via HTTP requests for purposes such as creating, updating, deleting and querying Auth objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the Auth Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the Auth service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the Auth service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the Auth service.
This service is configured to listen for HTTP requests on port `3011`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/auth-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/auth-api`
* **Production:** `https://workforceos.mindbricks.co/auth-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the Auth service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `Auth` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `Auth` service.
### Multi Tenant Architecture
The `Auth` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `Auth` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `Auth` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `Auth` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `Auth` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
Auth service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### User resource
*Resource Definition* : A data object that stores the user information and handles login settings.
*User Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **email** | String | | | * A string value to represent the user's email.* |
| **password** | String | | | * A string value to represent the user's password. It will be stored as hashed.* |
| **fullname** | String | | | *A string value to represent the fullname of the user* |
| **avatar** | String | | | *The avatar url of the user. A random avatar will be generated if not provided* |
| **roleId** | String | | | *A string value to represent the roleId of the user.* |
| **emailVerified** | Boolean | | | *A boolean value to represent the email verification status of the user.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
### UserGroup resource
*Resource Definition* : A data object that stores the user group information.
*UserGroup Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **groupName** | String | | | * A string value to represent the group name.* |
| **avatar** | String | | | * A string value to represent the groups icon.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
### UserGroupMember resource
*Resource Definition* : A data object that stores the members of the user group.
*UserGroupMember Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **groupId** | ID | | | * An ID value to represent the group that the user is asssigned as a memeber to.* |
| **userId** | ID | | | * An ID value to represent the user that is assgined as a member to the group.* |
| **ownerId** | ID | | | *An ID value to represent the admin user who assgined the member.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
### Company resource
*Resource Definition* : A data object that stores the information for company
*Company Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **name** | String | | | *A string value to represent one word name of the company* |
| **codename** | String | | | *A string value to represent a unique code name for the company which is generated automatically using name* |
| **fullname** | String | | | *A string value to represent the fullname of the company* |
| **avatar** | String | | | *A string value represent the url of the company avatar. Keep null for random avatar.* |
| **ownerId** | ID | | | *An ID value to represent the user id of company owner who created the tenant* |
| **industry** | String | | | *The industry the company operates in (e.g., Technology, Healthcare, Finance, etc.)* |
| **companySize** | String | | | *The size of the company (e.g., 1-10, 11-50, 51-200, etc.)* |
### UserAvatarsFile resource
*Resource Definition* : Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL.
*UserAvatarsFile Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **fileName** | String | | | *Original file name as uploaded by the client.* |
| **mimeType** | String | | | *MIME type of the uploaded file (e.g., image/png, application/pdf).* |
| **fileSize** | Integer | | | *File size in bytes.* |
| **accessKey** | String | | | *12-character random key for shareable access. Auto-generated on upload.* |
| **ownerId** | ID | | | *ID of the user who uploaded the file (from session).* |
| **fileData** | Blob | | | *Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.* |
| **metadata** | Object | | | *Optional JSON metadata for the file (tags, alt text, etc.).* |
| **userId** | ID | | | *Reference to the owner user record.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
### CompanyAvatarsFile resource
*Resource Definition* : Auto-generated file storage for the companyAvatars database bucket. Files are stored as BYTEA in PostgreSQL.
*CompanyAvatarsFile Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **fileName** | String | | | *Original file name as uploaded by the client.* |
| **mimeType** | String | | | *MIME type of the uploaded file (e.g., image/png, application/pdf).* |
| **fileSize** | Integer | | | *File size in bytes.* |
| **accessKey** | String | | | *12-character random key for shareable access. Auto-generated on upload.* |
| **ownerId** | ID | | | *ID of the user who uploaded the file (from session).* |
| **fileData** | Blob | | | *Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.* |
| **metadata** | Object | | | *Optional JSON metadata for the file (tags, alt text, etc.).* |
| **companyId** | ID | | | *Reference to the owner company record.* |
## Business Api
### `Get User` API
This api is used by admin roles or the users themselves to get the user profile information.
**Rest Route**
The `getUser` API REST controller can be triggered via the following route:
`/v1/users/:userId`
**Rest Request Parameters**
The `getUser` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userId | ID | true | request.params?.["userId"] |
**userId** : This id paremeter is used to query the required data object.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/users/:userId**
```js
axios({
method: 'GET',
url: `/v1/users/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Update User` API
This route is used by admins to update user profiles.
**Rest Route**
The `updateUser` API REST controller can be triggered via the following route:
`/v1/users/:userId`
**Rest Request Parameters**
The `updateUser` api has got 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**
```js
axios({
method: 'PATCH',
url: `/v1/users/${userId}`,
data: {
fullname:"String",
avatar:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"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**
```js
axios({
method: 'PATCH',
url: '/v1/profile',
data: {
fullname:"String",
avatar:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Create User` API
This api is used by admin roles to create a new user manually from admin panels
**Rest Route**
The `createUser` API REST controller can be triggered via the following route:
`/v1/users`
**Rest Request Parameters**
The `createUser` api has got 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"] |
| email | String | true | request.body?.["email"] |
| password | String | true | request.body?.["password"] |
| fullname | String | true | request.body?.["fullname"] |
**avatar** : The avatar url of the user. If not sent, a default random one will be generated.
**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**
```js
axios({
method: 'POST',
url: '/v1/users',
data: {
avatar:"String",
roleId:"String",
emailVerified:"Boolean",
email:"String",
password:"String",
fullname:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Delete User` API
This api is used by admins to delete user profiles.
**Rest Route**
The `deleteUser` API REST controller can be triggered via the following route:
`/v1/users/:userId`
**Rest Request Parameters**
The `deleteUser` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userId | ID | true | request.params?.["userId"] |
**userId** : This id paremeter is used to select the required data object that will be deleted
**REST Request**
To access the api you can use the **REST** controller with the path **DELETE /v1/users/:userId**
```js
axios({
method: 'DELETE',
url: `/v1/users/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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**
```js
axios({
method: 'DELETE',
url: '/v1/profile',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `List Users` API
The list of users is filtered by the tenantId.
**Rest Route**
The `listUsers` API REST controller can be triggered via the following route:
`/v1/users`
**Rest Request Parameters**
**Filter Parameters**
The `listUsers` api supports 3 optional filter parameters for filtering list results:
**email** (`String`): A string value to represent the user's email.
- Single (partial match, case-insensitive): `?email=`
- Multiple: `?email=&email=`
- Null: `?email=null`
**fullname** (`String`): A string value to represent the fullname of the user
- Single (partial match, case-insensitive): `?fullname=`
- Multiple: `?fullname=&fullname=`
- Null: `?fullname=null`
**roleId** (`String`): A string value to represent the roleId of the user.
- Single (partial match, case-insensitive): `?roleId=`
- Multiple: `?roleId=&roleId=`
- Null: `?roleId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/users**
```js
axios({
method: 'GET',
url: '/v1/users',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// email: '' // Filter by email
// fullname: '' // Filter by fullname
// roleId: '' // Filter by roleId
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "users",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"users": [
{
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Search Users` API
The list of users is filtered by the tenantId.
**Rest Route**
The `searchUsers` API REST controller can be triggered via the following route:
`/v1/searchusers`
**Rest Request Parameters**
The `searchUsers` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| keyword | String | true | request.query?.["keyword"] |
**keyword** :
**Filter Parameters**
The `searchUsers` api supports 1 optional filter parameter for filtering list results:
**roleId** (`String`): A string value to represent the roleId of the user.
- Single (partial match, case-insensitive): `?roleId=`
- Multiple: `?roleId=&roleId=`
- Null: `?roleId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/searchusers**
```js
axios({
method: 'GET',
url: '/v1/searchusers',
data: {
},
params: {
keyword:'"String"',
// Filter parameters (see Filter Parameters section above)
// roleId: '' // Filter by roleId
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "users",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"users": [
{
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Update Userrole` API
This route is used by admin roles to update the user role.The default role is 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**
```js
axios({
method: 'PATCH',
url: `/v1/userrole/${userId}`,
data: {
roleId:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"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**
```js
axios({
method: 'PATCH',
url: '/v1/profile/password',
data: {
oldPassword:"String",
newPassword:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"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**
```js
axios({
method: 'PATCH',
url: `/v1/userpasswordbyadmin/${userId}`,
data: {
password:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "PATCH",
"action": "update",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Get Briefuser` API
This route is used by public to get simple user profile information.
**Rest Route**
The `getBriefUser` API REST controller can be triggered via the following route:
`/v1/briefuser/:userId`
**Rest Request Parameters**
The `getBriefUser` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userId | ID | true | request.params?.["userId"] |
**userId** : This id paremeter is used to query the required data object.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/briefuser/:userId**
```js
axios({
method: 'GET',
url: `/v1/briefuser/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
This route's response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"user": {
"isActive": true
}
}
```
### `Stream Test` API
Test API for iterator action streaming via SSE.
**Rest Route**
The `streamTest` API REST controller can be triggered via the following route:
`/v1/streamtest/:userId`
**Rest Request Parameters**
The `streamTest` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userId | ID | true | request.params?.["userId"] |
**userId** : This id paremeter is used to query the required data object.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/streamtest/:userId**
```js
axios({
method: 'GET',
url: `/v1/streamtest/${userId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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"] |
| email | 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**
```js
axios({
method: 'POST',
url: '/v1/registercompanyowner',
data: {
avatar:"String",
socialCode:"String",
password:"String",
email:"String",
company:"Object",
fullname:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
},
"company": "Object"
}
```
### `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"] |
| email | 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**
```js
axios({
method: 'POST',
url: '/v1/registercompanyuser',
data: {
socialCode:"String",
password:"String",
email:"String",
fullname:"String",
avatar:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "user",
"method": "POST",
"action": "create",
"appVersion": "Version",
"rowCount": 1,
"user": {
"id": "ID",
"email": "String",
"password": "String",
"fullname": "String",
"avatar": "String",
"roleId": "String",
"emailVerified": "Boolean",
"companyId": "ID",
"isActive": true,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `Create Company` API
This route is used by Saas Admin to create a tenant (Company) manually without public registration. After creating the tenant, a user should be updated to be owner of this tenant.
**Rest Route**
The `createCompany` API REST controller can be triggered via the following route:
`/v1/companies`
**Rest Request Parameters**
The `createCompany` api has got 5 regular request parameters
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| avatar | String | | request.body?.["avatar"] |
| name | String | true | request.body?.["name"] |
| fullname | String | true | request.body?.["fullname"] |
| industry | String | false | request.body?.["industry"] |
| companySize | String | false | request.body?.["companySize"] |
**avatar** : A string value represent the url of the Company avatar. Keep null for random avatar.
**name** : A string value to represent one word name of the company
**fullname** : A string value to represent the fullname of the company
**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 **POST /v1/companies**
```js
axios({
method: 'POST',
url: '/v1/companies',
data: {
avatar:"String",
name:"String",
fullname:"String",
industry:"String",
companySize:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "201",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "POST",
"action": "create",
"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 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**
```js
axios({
method: 'GET',
url: '/v1/companies',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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 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**
```js
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.
```json
{
"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 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**
```js
axios({
method: 'GET',
url: '/v1/companyprofile',
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/companyaccounts/${companyId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?name=&name=`
- 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=`
- Multiple: `?codename=&codename=`
- Null: `?codename=null`
**fullname** (`String`): A string value to represent the fullname of the company
- Single (partial match, case-insensitive): `?fullname=`
- Multiple: `?fullname=&fullname=`
- 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=`
- Multiple: `?avatar=&avatar=`
- Null: `?avatar=null`
**ownerId** (`ID`): An ID value to represent the user id of company owner who created the tenant
- Single: `?ownerId=`
- Multiple: `?ownerId=&ownerId=`
- Null: `?ownerId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/companyaccounts**
```js
axios({
method: 'GET',
url: '/v1/companyaccounts',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// name: '' // Filter by name
// codename: '' // Filter by codename
// fullname: '' // Filter by fullname
// avatar: '' // Filter by avatar
// ownerId: '' // Filter by ownerId
}
});
```
**REST Response**
```json
{
"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": []
}
```
### `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**
```js
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.
```json
{
"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 Briefcompany` API
Get brief public information of a company by id. A public SaaS-level route.
**Rest Route**
The `getBriefCompany` API REST controller can be triggered via the following route:
`/v1/briefcompanies/:codename`
**Rest Request Parameters**
The `getBriefCompany` 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/briefcompanies/:codename**
```js
axios({
method: 'GET',
url: `/v1/briefcompanies/${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.
```json
{
"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
}
}
```
### `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**
```js
axios({
method: 'PATCH',
url: `/v1/companies/${companyId}`,
data: {
name:"String",
fullname:"String",
avatar:"String",
industry:"String",
companySize:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"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"
}
}
```
### `Delete Company` API
Delete a company by id. An admin route which can be called by admins or tenant owners.
**Rest Route**
The `deleteCompany` API REST controller can be triggered via the following route:
`/v1/companies/:companyId`
**Rest Request Parameters**
The `deleteCompany` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| companyId | ID | true | request.params?.["companyId"] |
**companyId** : 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/companies/:companyId**
```js
axios({
method: 'DELETE',
url: `/v1/companies/${companyId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "company",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"company": {
"id": "ID",
"name": "String",
"codename": "String",
"fullname": "String",
"avatar": "String",
"ownerId": "ID",
"industry": "String",
"companySize": "String",
"isActive": false,
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID"
}
}
```
### `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**
```js
axios({
method: 'POST',
url: '/v1/usergroups',
data: {
avatar:"String",
groupName:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'PATCH',
url: `/v1/usergroups/${userGroupId}`,
data: {
groupName:"String",
avatar:"String",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/usergroups/${userGroupId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/usergroups/${userGroupId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?groupName=&groupName=`
- Null: `?groupName=null`
**avatar** (`String`): A string value to represent the groups icon.
- Single (partial match, case-insensitive): `?avatar=`
- Multiple: `?avatar=&avatar=`
- Null: `?avatar=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/usergroups**
```js
axios({
method: 'GET',
url: '/v1/usergroups',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// groupName: '' // Filter by groupName
// avatar: '' // Filter by avatar
}
});
```
**REST Response**
```json
{
"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": []
}
```
### `Get Usergroupmember` API
This is a public route to get the user group member information.
**Rest Route**
The `getUserGroupMember` API REST controller can be triggered via the following route:
`/v1/usergroupmembers/:userGroupMemberId`
**Rest Request Parameters**
The `getUserGroupMember` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userGroupMemberId | ID | true | request.params?.["userGroupMemberId"] |
**userGroupMemberId** : 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/usergroupmembers/:userGroupMemberId**
```js
axios({
method: 'GET',
url: `/v1/usergroupmembers/${userGroupMemberId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userGroupMember",
"method": "GET",
"action": "get",
"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"
}
}
```
### `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**
```js
axios({
method: 'POST',
url: '/v1/usergroupmembers',
data: {
groupId:"ID",
userId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/usergroupmembers/${userGroupMemberId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**ownerId** (`ID`): An ID value to represent the admin user who assgined the member.
- Single: `?ownerId=`
- Multiple: `?ownerId=&ownerId=`
- Null: `?ownerId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/listusergroupmembers/:groupId**
```js
axios({
method: 'GET',
url: `/v1/listusergroupmembers/${groupId}`,
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// ownerId: '' // Filter by ownerId
}
});
```
**REST Response**
```json
{
"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": []
}
```
### `Get Useravatarsfile` API
**[Default get API]** — This is the designated default `get` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
**Rest Route**
The `getUserAvatarsFile` API REST controller can be triggered via the following route:
`/v1/useravatarsfiles/:userAvatarsFileId`
**Rest Request Parameters**
The `getUserAvatarsFile` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] |
**userAvatarsFileId** : This id paremeter is used to query the required data object.
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles/:userAvatarsFileId**
```js
axios({
method: 'GET',
url: `/v1/useravatarsfiles/${userAvatarsFileId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userAvatarsFile",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"userAvatarsFile": {
"id": "ID",
"fileName": "String",
"mimeType": "String",
"fileSize": "Integer",
"accessKey": "String",
"ownerId": "ID",
"fileData": "Blob",
"metadata": "Object",
"userId": "ID",
"companyId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": true
}
}
```
### `List Useravatarsfiles` API
**[Default list API]** — This is the designated default `list` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
**Rest Route**
The `listUserAvatarsFiles` API REST controller can be triggered via the following route:
`/v1/useravatarsfiles`
**Rest Request Parameters**
**Filter Parameters**
The `listUserAvatarsFiles` api supports 3 optional filter parameters for filtering list results:
**mimeType** (`String`): MIME type of the uploaded file (e.g., image/png, application/pdf).
- Single (partial match, case-insensitive): `?mimeType=`
- Multiple: `?mimeType=&mimeType=`
- Null: `?mimeType=null`
**ownerId** (`ID`): ID of the user who uploaded the file (from session).
- Single: `?ownerId=`
- Multiple: `?ownerId=&ownerId=`
- Null: `?ownerId=null`
**userId** (`ID`): Reference to the owner user record.
- Single: `?userId=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/useravatarsfiles**
```js
axios({
method: 'GET',
url: '/v1/useravatarsfiles',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// mimeType: '' // Filter by mimeType
// ownerId: '' // Filter by ownerId
// userId: '' // Filter by userId
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userAvatarsFiles",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"userAvatarsFiles": [
{
"id": "ID",
"fileName": "String",
"mimeType": "String",
"fileSize": "Integer",
"accessKey": "String",
"ownerId": "ID",
"fileData": "Blob",
"metadata": "Object",
"userId": "ID",
"companyId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Delete Useravatarsfile` API
**[Default delete API]** — This is the designated default `delete` API for the `userAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
**Rest Route**
The `deleteUserAvatarsFile` API REST controller can be triggered via the following route:
`/v1/useravatarsfiles/:userAvatarsFileId`
**Rest Request Parameters**
The `deleteUserAvatarsFile` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| userAvatarsFileId | ID | true | request.params?.["userAvatarsFileId"] |
**userAvatarsFileId** : This id paremeter is used to select the required data object that will be deleted
**REST Request**
To access the api you can use the **REST** controller with the path **DELETE /v1/useravatarsfiles/:userAvatarsFileId**
```js
axios({
method: 'DELETE',
url: `/v1/useravatarsfiles/${userAvatarsFileId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "userAvatarsFile",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"userAvatarsFile": {
"id": "ID",
"fileName": "String",
"mimeType": "String",
"fileSize": "Integer",
"accessKey": "String",
"ownerId": "ID",
"fileData": "Blob",
"metadata": "Object",
"userId": "ID",
"companyId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": false
}
}
```
### `Get Companyavatarsfile` API
**[Default get API]** — This is the designated default `get` API for the `companyAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
**Rest Route**
The `getCompanyAvatarsFile` API REST controller can be triggered via the following route:
`/v1/companyavatarsfiles/:companyAvatarsFileId`
**Rest Request Parameters**
The `getCompanyAvatarsFile` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| companyAvatarsFileId | ID | true | request.params?.["companyAvatarsFileId"] |
**companyAvatarsFileId** : 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/companyavatarsfiles/:companyAvatarsFileId**
```js
axios({
method: 'GET',
url: `/v1/companyavatarsfiles/${companyAvatarsFileId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companyAvatarsFile",
"method": "GET",
"action": "get",
"appVersion": "Version",
"rowCount": 1,
"companyAvatarsFile": {
"id": "ID",
"fileName": "String",
"mimeType": "String",
"fileSize": "Integer",
"accessKey": "String",
"ownerId": "ID",
"fileData": "Blob",
"metadata": "Object",
"companyId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": true
}
}
```
### `List Companyavatarsfiles` API
**[Default list API]** — This is the designated default `list` API for the `companyAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
**Rest Route**
The `listCompanyAvatarsFiles` API REST controller can be triggered via the following route:
`/v1/companyavatarsfiles`
**Rest Request Parameters**
**Filter Parameters**
The `listCompanyAvatarsFiles` api supports 3 optional filter parameters for filtering list results:
**mimeType** (`String`): MIME type of the uploaded file (e.g., image/png, application/pdf).
- Single (partial match, case-insensitive): `?mimeType=`
- Multiple: `?mimeType=&mimeType=`
- Null: `?mimeType=null`
**ownerId** (`ID`): ID of the user who uploaded the file (from session).
- Single: `?ownerId=`
- Multiple: `?ownerId=&ownerId=`
- Null: `?ownerId=null`
**companyId** (`ID`): Reference to the owner company record.
- Single: `?companyId=`
- Multiple: `?companyId=&companyId=`
- Null: `?companyId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/companyavatarsfiles**
```js
axios({
method: 'GET',
url: '/v1/companyavatarsfiles',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// mimeType: '' // Filter by mimeType
// ownerId: '' // Filter by ownerId
// companyId: '' // Filter by companyId
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companyAvatarsFiles",
"method": "GET",
"action": "list",
"appVersion": "Version",
"rowCount": "\"Number\"",
"companyAvatarsFiles": [
{
"id": "ID",
"fileName": "String",
"mimeType": "String",
"fileSize": "Integer",
"accessKey": "String",
"ownerId": "ID",
"fileData": "Blob",
"metadata": "Object",
"companyId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": true
},
{},
{}
],
"paging": {
"pageNumber": "Number",
"pageRowCount": "NUmber",
"totalRowCount": "Number",
"pageCount": "Number"
},
"filters": [],
"uiPermissions": []
}
```
### `Delete Companyavatarsfile` API
**[Default delete API]** — This is the designated default `delete` API for the `companyAvatarsFile` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
**Rest Route**
The `deleteCompanyAvatarsFile` API REST controller can be triggered via the following route:
`/v1/companyavatarsfiles/:companyAvatarsFileId`
**Rest Request Parameters**
The `deleteCompanyAvatarsFile` api has got 1 regular request parameter
| Parameter | Type | Required | Population |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| companyAvatarsFileId | ID | true | request.params?.["companyAvatarsFileId"] |
**companyAvatarsFileId** : 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/companyavatarsfiles/:companyAvatarsFileId**
```js
axios({
method: 'DELETE',
url: `/v1/companyavatarsfiles/${companyAvatarsFileId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "companyAvatarsFile",
"method": "DELETE",
"action": "delete",
"appVersion": "Version",
"rowCount": 1,
"companyAvatarsFile": {
"id": "ID",
"fileName": "String",
"mimeType": "String",
"fileSize": "Integer",
"accessKey": "String",
"ownerId": "ID",
"fileData": "Blob",
"metadata": "Object",
"companyId": "ID",
"recordVersion": "Integer",
"createdAt": "Date",
"updatedAt": "Date",
"_owner": "ID",
"isActive": false
}
}
```
### Authentication Specific Routes
### Route: login
*Route Definition*: Handles the login process by verifying user credentials and generating an authenticated session.
*Route Type*: login
*Access Routes*:
- `GET /login`: Returns the HTML login page
(not a frontend module, typically used in browser-based contexts for test purpose to make sending POST /login easier).
- `POST /login`: Accepts credentials, verifies the user, creates a session, and returns a JWT access token.
#### Parameters
| Parameter | Type | Required | Population |
|-------------|----------|----------|-----------------------------|
| username | String | Yes | `request.body.username` |
| password | String | Yes | `request.body.password` |
#### Notes
- This route accepts login credentials and creates an authenticated session if credentials are valid.
- On success, the response will:
- Set a cookie named `projectname-access-token[-tenantCodename]` with the JWT token.
- Include the token in the response headers under the same name.
- Return the full `session` object in the JSON body.
- Note that `username` parameter should have the email of the user as value.
You can also send an `email` parameter instead of `username` parameter.
If both sent only `username` parameter will be read.
```js
// Sample POST /login call
axios.post("/login", {
username: "user@example.com",
password: "securePassword"
});
````
**Success Response**
Returns the authenticated session object with a status code `200 OK`.
A secure HTTP-only cookie and an access token header are included in the response.
```json
{
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
...
}
````
**Error Responses**
* **401 Unauthorized:** Invalid username or password.
* **403 Forbidden:** Login attempt rejected due to pending email/mobile verification or 2FA requirements.
* **400 Bad Request:** Missing credentials in the request.
### Route: logout
*Route Definition*: Logs the user out by terminating the current session and clearing the access token.
*Route Type*: logout
*Access Route*: `POST /logout`
#### Parameters
This route does not require any parameters in the body or query.
#### Behavior
- Invalidates the current session on the server (if stored).
- Clears the access token cookie (`projectname-access-token[-tenantCodename]`) from the client.
- Responds with a 200 status and a simple confirmation object.
```js
// Sample POST /logout call
axios.post("/logout", {}, {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Notes**
* This route is public, meaning it can be called without a session or token.
* If the session is active, the server will clear associated session state and cookies.
* The logout behavior may vary slightly depending on whether you're using cookie-based or header-based token management.
**Error Responses**
00200 OK:** Always returned, regardless of whether a session existed.
Logout is treated as idempotent.
### Route: publickey
*Route Definition*: Returns the public RSA key used to verify JWT access tokens issued by the auth service.
*Route Type*: publicKeyFetch
*Access Route*: `GET /publickey`
#### Parameters
| Parameter | Type | Required | Population |
|-----------|--------|----------|--------------------|
| keyId | String | No | `request.query.keyId` |
- `keyId` is optional.
If provided, retrieves the public key corresponding to the specific `keyId`.
If omitted, retrieves the current active public key (`global.currentKeyId`).
#### Behavior
- Reads the requested RSA public key file from the server filesystem.
- If the key exists, returns it along with its `keyId`.
- If the key does not exist, returns a 404 error.
```js
// Sample GET /publickey call
axios.get("/publickey", {
params: {
keyId: "currentKeyIdOptional"
}
});
````
**Success Response**
Returns the active public key and its associated keyId.
```json
{
"keyId": "a1b2c3d4",
"keyData": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhki...\n-----END PUBLIC KEY-----"
}
````
**Error Responses**
**404 Not Found:** Public key file could not be found on the server.
### Token Key Management
Mindbricks uses RSA key pairs to sign and verify JWT access tokens securely.
While the auth service signs each token with a private key, other services within the system — or external clients — need the corresponding **public key** to verify the authenticity and integrity of received tokens.
The `/publickey` endpoint allows services and clients to dynamically fetch the currently active public key, ensuring that token verification remains secure even if key rotation is performed.
> **Note**:
> The `/publickey` route is not intended for direct frontend (browser) consumption.
> Instead, it is primarily used by trusted backend services, APIs, or middleware systems that need to independently verify access tokens issued by the auth service — without making verification-dependent API calls to the auth service itself.
Accessing the public key is crucial for validating user sessions efficiently and maintaining a decentralized trust model across your platform.
### Route: relogin
*Route Definition*: Performs a silent login by verifying the current access token, refreshing the session, and returning a new access token along with updated user information.
*Route Type*: sessionRefresh
*Access Route*: `GET /relogin`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Validates the access token associated with the request.
- If the token is valid:
- Re-authenticates the user using the session's user ID.
- Fetches the most up-to-date user information from the database.
- Generates a new session object with a **new session ID** and **new access token**.
- If the token is invalid or missing, returns a 401 Unauthorized error.
```js
// Example call to refresh session
axios.get("/relogin", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns a new session object, refreshed from database data.
```json
{
"sessionId": "new-session-uuid",
"userId": "user-uuid",
"email": "user@example.com",
"roleId": "admin",
"accessToken": "new-jwt-token",
...
}
````
**Error Responses**
* **401 Unauthorized**: Token is missing, invalid, or session cannot be re-established.
```json
{
"status": "ERR",
"message": "Cannot relogin"
}
````
**Notes**
- The `/relogin` route is commonly used for **silent login flows**, especially after page reloads or token-based auto-login mechanisms.
- It triggers internal logic (`req.userAuthUpdate = true`) to signal that the session should be re-initialized and repopulated.
- It is not a simple session lookup — it performs a fresh authentication pass using the session's user context.
- The refreshed session ensures any updates to user profile, roles, or permissions are immediately reflected.
> **Tip:**
> This route is ideal when you want to **rebuild a user's session** in the frontend without requiring them to manually log in again.
## Verification Services — Email Verification
Email verification is a two-step flow that ensures a user's email address is verified and trusted by the system.
All verification services, including email verification, are located under the `/verification-services` base path.
### When is Email Verification Triggered?
- After user registration, if `emailVerificationRequiredForLogin` is active.
- During a separate user action to verify or update email addresses.
- When login fails with `EmailVerificationNeeded` and frontend initiates verification.
### Email Verification Flow
1. **Frontend calls `/verification-services/email-verification/start`** with the user's email address.
- Mindbricks checks if the email is already verified.
- A secret code is generated and stored in the cache linked to the user.
- The code is sent to the user's email or returned in the response (only in development environments for easier testing).
2. **User receives the code and enters it into the frontend application.**
3. **Frontend calls `/verification-services/email-verification/complete`** with the `email` and the received `secretCode`.
- Mindbricks checks that the code is valid, not expired, and matches.
- If valid, the user’s `emailVerified` flag is set to `true`, and a success response is returned.
---
## API Endpoints
### POST `/verification-services/email-verification/start`
**Purpose**
Starts the email verification process by generating and sending a secret verification code.
#### Request Body
| Parameter | Type | Required | Description |
|-----------|--------|----------|-----------------------------|
| email | String | Yes | The email address to verify |
```json
{
"email": "user@example.com"
}
````
#### Success Response
Secret code details (in development environment). Confirms that the verification step has been started.
```json
{
"userId": "user-uuid",
"email": "user@example.com",
"secretCode": "123456",
"expireTime": 86400,
"date": "2024-04-29T10:00:00.000Z"
}
````
> ⚠️ In production, the secret code is only sent via email, not exposed in the API response.
#### Error Responses
- `400 Bad Request`: Email already verified.
- `403 Forbidden`: Sending a code too frequently (anti-spam).
---
### POST `/verification-services/email-verification/complete`
**Purpose**
Completes the email verification by validating the secret code.
#### Request Body
| Parameter | Type | Required | Description |
|-------------|--------|----------|-------------------------------------|
| email | String | Yes | The user email being verified |
| secretCode | String | Yes | The secret code received via email |
```json
{
"email": "user@example.com",
"secretCode": "123456"
}
````
#### Success Response
Returns confirmation that the email has been verified.
```json
{
"userId": "user-uuid",
"email": "user@example.com",
"isVerified": true
}
````
#### Error Responses
- `403 Forbidden`:
- Secret code mismatch
- Secret code expired
- No ongoing verification found
---
## Important Behavioral Notes
### Resend Throttling
You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds).
### Expiration Handling
Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day).
### One Code Per Session
Only one active verification session per user is allowed at a time.
> 💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps.
## Verification Services — Mobile Verification
Mobile verification is a two-step flow that ensures a user's mobile number is verified and trusted by the system.
All verification services, including mobile verification, are located under the `/verification-services` base path.
### When is Mobile Verification Triggered?
- After user registration, if `mobileVerificationRequiredForLogin` is active.
- During a separate user action to verify or update mobile numbers.
- When login fails with `MobileVerificationNeeded` and frontend initiates verification.
### Mobile Verification Flow
1. **Frontend calls `/verification-services/mobile-verification/start`** with the user's email address (used to locate the user).
- Mindbricks checks if the mobile number is already verified.
- A secret code is generated and stored in the cache linked to the user.
- The code is sent to the user's mobile via SMS or returned in the response (only in development environments for easier testing).
2. **User receives the code and enters it into the frontend application.**
3. **Frontend calls `/verification-services/mobile-verification/complete`** with the `email` and the received `secretCode`.
- Mindbricks checks that the code is valid, not expired, and matches.
- If valid, the user’s `mobileVerified` flag is set to `true`, and a success response is returned.
---
## API Endpoints
### POST `/verification-services/mobile-verification/start`
**Purpose**:
Starts the mobile verification process by generating and sending a secret verification code.
#### Request Body
| Parameter | Type | Required | Description |
|-----------|--------|----------|-------------------------------------|
| email | String | Yes | The email address associated with the mobile number to verify |
```json
{
"email": "user@example.com"
}
````
**Success Response**
Secret code details (in development environment). Confirms that the verification step has been started.
```json
{
"userId": "user-uuid",
"mobile": "+15551234567",
"secretCode": "123456",
"expireTime": 86400,
"date": "2024-04-29T10:00:00.000Z"
}
````
⚠️ In production, the secret code is only sent via SMS, not exposed in the API response.
**Error Responses**
- 400 Bad Request: Mobile already verified.
- 403 Forbidden: Sending a code too frequently (anti-spam).
---
### POST `/verification-services/mobile-verification/complete`
**Purpose**:
Completes the mobile verification by validating the secret code.
#### Request Body
| Parameter | Type | Required | Description |
|-------------|--------|----------|------------------------------------|
| email | String | Yes | The user's email being verified |
| secretCode | String | Yes | The secret code received via SMS |
```json
{
"email": "user@example.com",
"secretCode": "123456"
}
````
**Success Response**
Returns confirmation that the mobile number has been verified.
```json
{
"userId": "user-uuid",
"mobile": "+15551234567",
"isVerified": true
}
````
**Error Responses**
403 Forbidden:
- Secret code mismatch
- Secret code expired
- No ongoing verification found
---
## Important Behavioral Notes
**Resend Throttling**:
You can only request a new verification code after a cooldown period (`resendTimeWindow`, e.g., 60 seconds).
**Expiration Handling**:
Verification codes expire after a configured period (`expireTimeWindow`, e.g., 1 day).
**One Code Per Session**:
Only one active verification session per user is allowed at a time.
💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps.
## Verification Services — Email 2FA Verification
Email 2FA (Two-Factor Authentication) provides an additional layer of security by requiring users to confirm their identity using a secret code sent to their email address. This process is used in login flows or sensitive actions that need extra verification.
All verification services, including 2FA, are located under the `/verification-services` base path.
### When is Email 2FA Triggered?
- During login flows where `sessionNeedsEmail2FA` is `true`
- When the backend enforces two-factor authentication for a sensitive operation
### Email 2FA Flow
1. **Frontend calls `/verification-services/email-2factor-verification/start`** with the user's id, session id, client info, and reason.
- Mindbricks identifies the user and checks if a cooldown period applies.
- A new secret code is generated and stored, linked to the current session ID.
- The code is sent via email or returned in development environments.
2. **User receives the code and enters it into the frontend application.**
3. **Frontend calls `/verification-services/email-2factor-verification/complete`** with the `userId`, `sessionId`, and the `secretCode`.
- Mindbricks verifies the code, validates the session, and updates the session to remove the 2FA requirement.
---
## API Endpoints
### POST `/verification-services/email-2factor-verification/start`
**Purpose**:
Starts the email-based 2FA process by generating and sending a verification code.
#### Request Body
| Parameter | Type | Required | Description |
|-----------|--------|----------|-----------------------------------------------|
| userId | String | Yes | The user’s ID |
| sessionId | String | Yes | The current session ID |
| client | String | No | Optional client tag or context |
| reason | String | No | Optional reason for triggering 2FA |
```json
{
"userId": "user-uuid",
"sessionId": "session-uuid",
"client": "login-page",
"reason": "Login requires email 2FA"
}
````
#### Success Response
```json
{
"sessionId": "session-uuid",
"userId": "user-uuid",
"email": "user@example.com",
"secretCode": "123456",
"expireTime": 300,
"date": "2024-04-29T10:00:00.000Z"
}
````
⚠️ In production, the `secretCode` is only sent via email, not exposed in the API response.
#### Error Responses
- **403 Forbidden**: Sending a code too frequently (anti-spam)
- **401 Unauthorized**: User session not found
---
### POST `/verification-services/email-2factor-verification/complete`
**Purpose**:
Completes the email 2FA process by validating the secret code and session.
#### Request Body
| Parameter | Type | Required | Description |
|-------------|--------|----------|--------------------------------------------------|
| userId | String | Yes | The user’s ID |
| sessionId | String | Yes | The session ID the code is tied to |
| secretCode | String | Yes | The secret code received via email |
```json
{
"userId": "user-uuid",
"sessionId": "session-uuid",
"secretCode": "123456"
}
````
#### Success Response
Returns an updated session with 2FA disabled:
```json
{
"sessionId": "session-uuid",
"userId": "user-uuid",
"sessionNeedsEmail2FA": false,
...
}
````
#### Error Responses
- **403 Forbidden**:
- Secret code mismatch
- Secret code expired
- Verification step not found
---
### Important Behavioral Notes
- **One Code Per Session**: Only one active code can be issued per session.
- **Resend Throttling**: Code requests are throttled based on `resendTimeWindow` (e.g., 60 seconds).
- **Expiration**: Codes expire after `expireTimeWindow` (e.g., 5 minutes).
- 💡 Mindbricks manages session cache, spam control, expiration tracking, and event notifications for all 2FA steps.
## Verification Services — Mobile 2FA Verification
Mobile 2FA (Two-Factor Authentication) is a security mechanism that adds an extra layer of authentication using a user's verified mobile number.
All verification services, including mobile 2FA, are accessible under the `/verification-services` base path.
### When is Mobile 2FA Triggered?
- During login or critical actions requiring step-up authentication.
- When the session has a flag `sessionNeedsMobile2FA = true`.
- When login or session verification fails with `MobileVerificationNeeded`, indicating 2FA is required.
### Mobile 2FA Verification Flow
1. **Frontend calls `/verification-services/mobile-2factor-verification/start`** with the user's id, session id, client info, and reason.
- Mindbricks finds the user by id.
- Verifies that the user has a verified mobile number.
- A secret code is generated and cached against the session.
- The code is sent to the user's verified mobile number or returned in the response (only in development environments).
2. **User receives the code and enters it in the frontend app.**
3. **Frontend calls `/verification-services/mobile-2factor-verification/complete`** with the `userId`, `sessionId`, and `secretCode`.
- Mindbricks validates the code for expiration and correctness.
- If valid, the session flag `sessionNeedsMobile2FA` is cleared.
- A refreshed session object is returned.
---
## API Endpoints
### POST `/verification-services/mobile-2factor-verification/start`
**Purpose**:
Initiates mobile-based 2FA by generating and sending a secret code.
#### Request Body
| Parameter | Type | Required | Description |
|-----------|--------|----------|-----------------------------------------------|
| userId | String | Yes | The user’s ID |
| sessionId | String | Yes | The current session ID |
| client | String | No | Optional client tag or context |
| reason | String | No | Optional reason for triggering 2FA |
```json
{
"userId": "user-uuid",
"sessionId": "session-uuid",
"client": "login-page",
"reason": "Login requires mobile 2FA"
}
````
**Success Response**
Returns the generated code (only in development), expiration info, and metadata.
```json
{
"userId": "user-uuid",
"sessionId": "session-uuid",
"mobile": "+15551234567",
"secretCode": "654321",
"expireTime": 300,
"date": "2024-04-29T11:00:00.000Z"
}
````
⚠️ In production environments, the secret code is not included in the response and is instead delivered via SMS.
**Error Responses**
- 403 Forbidden: Mobile number not verified.
- 403 Forbidden: Code resend attempted before cooldown period (`resendTimeWindow`).
- 401 Unauthorized: Email not recognized or session invalid.
---
### POST `/verification-services/mobile-2factor-verification/complete`
**Purpose**:
Completes mobile 2FA verification by validating the secret code and updating the session.
#### Request Body
| Parameter | Type | Required | Description |
|-------------|--------|----------|-------------------------------------|
| userId | String | Yes | ID of the user |
| sessionId | String | Yes | ID of the session |
| secretCode | String | Yes | The 6-digit code received via SMS |
```json
{
"userId": "user-uuid",
"sessionId": "session-uuid",
"secretCode": "654321"
}
````
**Success Response**
Returns the updated session with `sessionNeedsMobile2FA: false`.
```json
{
"sessionId": "session-uuid",
"userId": "user-uuid",
"sessionNeedsMobile2FA": false,
"accessToken": "jwt-token",
"expiresIn": 86400
}
````
**Error Responses**
- 403 Forbidden: Code mismatch or expired.
- 403 Forbidden: No ongoing verification found.
- 401 Unauthorized: Session does not exist or is invalid.
---
### Behavioral Notes
- **Rate Limiting**: A user can only request a new mobile 2FA code after the cooldown period (`resendTimeWindow`, e.g., 60 seconds).
- **Expiration**: Mobile 2FA codes expire after the configured time (`expireTimeWindow`, e.g., 5 minutes).
- **Session Integrity**: Verification status is tied to the session; incorrect sessionId will invalidate the attempt.
💡 Mindbricks handles session integrity, rate limiting, and secure code delivery to ensure a robust mobile 2FA process.
## Verification Services — Password Reset by Email
Password Reset by Email enables a user to securely reset their password using a secret code sent to their registered email address.
All verification services, including password reset by email, are located under the `/verification-services` base path.
### When is Password Reset by Email Triggered?
- When a user requests to reset their password by providing their email address.
- This service is typically exposed on a “Forgot Password?” flow in the frontend.
### Password Reset Flow
1. **Frontend calls `/verification-services/password-reset-by-email/start`** with the user's email.
- Mindbricks checks if the user exists and if the email is registered.
- A secret code is generated and stored in the cache linked to the user.
- The code is sent to the user's email, or returned in the response (in development environments only for testing).
2. **User receives the code and enters it into the frontend along with the new password.**
3. **Frontend calls `/verification-services/password-reset-by-email/complete`** with the `email`, the `secretCode`, and the new `password`.
- Mindbricks checks that the code is valid, not expired, and matches.
- If valid, the user’s password is reset, their `emailVerified` flag is set to `true`, and a success response is returned.
---
## API Endpoints
### POST `/verification-services/password-reset-by-email/start`
**Purpose**:
Starts the password reset process by generating and sending a secret verification code.
#### Request Body
| Parameter | Type | Required | Description |
|-----------|--------|----------|-------------------------------------|
| email | String | Yes | The email address of the user |
```json
{
"email": "user@example.com"
}
````
**Success Response**
Returns secret code details (only in development environment) and confirmation that the verification step has been started.
```json
{
"userId": "user-uuid",
"email": "user@example.com",
"secretCode": "123456",
"expireTime": 86400,
"date": "2024-04-29T10:00:00.000Z"
}
````
⚠️ In production, the secret code is only sent via email and not exposed in the API response.
**Error Responses**
- `401 NotAuthenticated`: Email address not found or not associated with a user.
- `403 Forbidden`: Sending a code too frequently (spam prevention).
---
### POST `/verification-services/password-reset-by-email/complete`
**Purpose**:
Completes the password reset process by validating the secret code and updating the user's password.
#### Request Body
| Parameter | Type | Required | Description |
|-------------|--------|----------|----------------------------------------------|
| email | String | Yes | The email address of the user |
| secretCode | String | Yes | The code received via email |
| password | String | Yes | The new password the user wants to set |
```json
{
"email": "user@example.com",
"secretCode": "123456",
"password": "newSecurePassword123"
}
````
**Success Response**
```json
{
"userId": "user-uuid",
"email": "user@example.com",
"isVerified": true
}
````
**Error Responses**
- `403 Forbidden`:
- Secret code mismatch
- Secret code expired
- No ongoing verification found
---
## Important Behavioral Notes
### Resend Throttling:
A new verification code can only be requested after a cooldown period (configured via `resendTimeWindow`, e.g., 60 seconds).
### Expiration Handling:
Verification codes automatically expire after a predefined period (`expireTimeWindow`, e.g., 1 day).
### Session & Event Handling:
Mindbricks manages:
- Spam prevention
- Code caching per user
- Expiration logic
- Verification start/complete events
## Verification Services — Password Reset by Mobile
Password reset by mobile provides users with a secure mechanism to reset their password using a verification code sent via SMS to their registered mobile number.
All verification services, including password reset by mobile, are located under the `/verification-services` base path.
### When is Password Reset by Mobile Triggered?
- When a user forgets their password and selects the mobile reset option.
- When a user explicitly initiates password recovery via mobile on the login or help screen.
### Password Reset by Mobile Flow
1. **Frontend calls `/verification-services/password-reset-by-mobile/start`** with the user's mobile number or associated identifier.
- Mindbricks checks if a user with the given mobile exists.
- A secret code is generated and stored in the cache for that user.
- The code is sent to the user's mobile (or returned in development environments for testing).
2. **User receives the code via SMS and enters it into the frontend app.**
3. **Frontend calls `/verification-services/password-reset-by-mobile/complete`** with the user's `email`, the `secretCode`, and the new `password`.
- Mindbricks validates the secret code and its expiration.
- If valid, it updates the user's password and returns a success response.
---
## API Endpoints
### POST `/verification-services/password-reset-by-mobile/start`
**Purpose**:
Initiates the mobile-based password reset by sending a verification code to the user's mobile.
#### Request Body
| Parameter | Type | Required | Description |
|-----------|--------|----------|------------------------------|
| mobile | String | Yes | The mobile number to verify |
```json
{
"mobile": "+905551234567"
}
````
### Success Response
Returns the verification context (code returned only in development):
```json
{
"userId": "user-uuid",
"mobile": "+905551234567",
"secretCode": "123456",
"expireTime": 86400,
"date": "2024-04-29T10:00:00.000Z"
}
````
⚠️ In production, the `secretCode` is not included in the response and is only sent via SMS.
### Error Responses
- **400 Bad Request**: Mobile already verified
- **403 Forbidden**: Rate-limited (code already sent recently)
- **404 Not Found**: User with provided mobile not found
---
### POST `/verification-services/password-reset-by-mobile/complete`
**Purpose**:
Finalizes the password reset process by validating the received verification code and updating the user’s password.
#### Request Body
| Parameter | Type | Required | Description |
|-------------|--------|----------|-------------------------------------------------|
| email | String | Yes | The email address of the user |
| secretCode | String | Yes | The code received via SMS |
| password | String | Yes | The new password to assign |
```json
{
"email": "user@example.com",
"secretCode": "123456",
"password": "NewSecurePassword123!"
}
````
### Success Response
```json
{
"userId": "user-uuid",
"mobile": "+905551234567",
"isVerified": true
}
````
---
### Important Behavioral Notes
- **Throttling**: Codes can only be resent after a delay defined by `resendTimeWindow` (e.g., 60 seconds).
- **Expiration**: Codes expire after the `expireTimeWindow` (e.g., 1 day).
- **One Active Session**: Only one active password reset session is allowed per user at a time.
- **Session-less**: This flow does not require an active session — it works for unauthenticated users.
💡 Mindbricks handles spam protection, session caching, and event-based logging (for both start and complete operations) as part of the verification service base class.
## Verification Method Types
### 🧾 For byCode Verifications
This verification type requires the user to manually enter a 6-digit code.
**Frontend Action**:
Display a secure input page where the user can enter the code they received via email or SMS. After collecting the code and any required metadata (such as `userId` or `sessionId`), make a `POST` request to the corresponding `/complete` endpoint.
---
### 🔗 For byLink Verifications
This verification type uses a clickable link embedded in an email (or SMS message).
**Frontend Action**:
The link points to a `GET` page in your frontend that parses `userId` and `code` from the query string and sends them to the backend via a `POST` request to the corresponding `/complete` endpoint. This enables one-click verification without requiring the user to type in a code.
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-employeeprofile-service
**Version:** `1.0.16`
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..
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the EmployeeProfile Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our EmployeeProfile Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the EmployeeProfile Service via HTTP requests for purposes such as creating, updating, deleting and querying EmployeeProfile objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the EmployeeProfile Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the EmployeeProfile service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the EmployeeProfile service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the EmployeeProfile service.
This service is configured to listen for HTTP requests on port `3001`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/employeeprofile-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/employeeprofile-api`
* **Production:** `https://workforceos.mindbricks.co/employeeprofile-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the EmployeeProfile service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `EmployeeProfile` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `EmployeeProfile` service.
### Multi Tenant Architecture
The `EmployeeProfile` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `EmployeeProfile` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `EmployeeProfile` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `EmployeeProfile` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `EmployeeProfile` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
EmployeeProfile service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### EmployeeProfile resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **userId** | ID | | | *Reference to the auth user for this employee profile.* |
| **employmentStartDate** | Date | | | *Employee's official employment start date.* |
| **position** | String | | | *Employee's job title or position* |
| **contractType** | Enum | | | *Type of employment contract for this employee.* |
| **salary** | Double | | | *Employee's salary for reporting (managers/admins only).* |
| **departmentId** | ID | | | *Reference to the department (userGroup) this employee belongs to.* |
| **managerId** | ID | | | *ID of the assigned manager or supervisor (userId from auth:user).* |
| **notes** | Text | | | *Manager/admin internal notes (not visible to employees).* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### contractType Enum Property
*Property Definition* : Type of employment contract for this employee.*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **permanent** | `"permanent""` | 0 |
| **temporary** | `"temporary""` | 1 |
| **contract** | `"contract""` | 2 |
### EmployeeDocument resource
*Resource Definition* : Document or certification attached to an employee profile. E.g., work permit, certification, or contract files.
*EmployeeDocument Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **employeeProfileId** | ID | | | *Reference to the related employeeProfile record.* |
| **documentType** | String | | | *Type of document (e.g., ID, contract, certification).* |
| **documentUrl** | String | | | *URL to the file storage location or bucket for this document.* |
| **validUntil** | Date | | | *Expiration date of document, if applicable. Used for tracking compliance/renewal.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
## Business Api
### `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**
```js
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**
```json
{
"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**
```js
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**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/employeeprofiles/${employeeProfileId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?userId=&userId=`
- 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-`, `$lin-`
- Null: `?employmentStartDate=null`
**departmentId** (`ID`): Reference to the department (userGroup) this employee belongs to.
- Single: `?departmentId=`
- Multiple: `?departmentId=&departmentId=`
- Null: `?departmentId=null`
**managerId** (`ID`): ID of the assigned manager or supervisor (userId from auth:user).
- Single: `?managerId=`
- Multiple: `?managerId=&managerId=`
- Null: `?managerId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/employeeprofiles**
```js
axios({
method: 'GET',
url: '/v1/employeeprofiles',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// employmentStartDate: '' // Filter by employmentStartDate
// departmentId: '' // Filter by departmentId
// managerId: '' // Filter by managerId
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'POST',
url: '/v1/employeedocuments',
data: {
employeeProfileId:"ID",
documentType:"String",
documentUrl:"String",
validUntil:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'PATCH',
url: `/v1/employeedocuments/${employeeDocumentId}`,
data: {
documentType:"String",
documentUrl:"String",
validUntil:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/employeedocuments/${employeeDocumentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?employeeProfileId=&employeeProfileId=`
- 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-`, `$lin-`
- Null: `?validUntil=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/employeedocuments**
```js
axios({
method: 'GET',
url: '/v1/employeedocuments',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// employeeProfileId: '' // Filter by employeeProfileId
// validUntil: '' // Filter by validUntil
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/employeeprofiles/${employeeProfileId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/employeedocuments/${employeeDocumentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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"
}
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-schedulemanagement-service
**Version:** `1.0.11`
Microservice managing shift scheduling, shift templates, assignment of users/departments to shifts, and schedule conflict detection for WorkforceOS.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the ScheduleManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our ScheduleManagement Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the ScheduleManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying ScheduleManagement objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the ScheduleManagement Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the ScheduleManagement service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the ScheduleManagement service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the ScheduleManagement service.
This service is configured to listen for HTTP requests on port `3001`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/schedulemanagement-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/schedulemanagement-api`
* **Production:** `https://workforceos.mindbricks.co/schedulemanagement-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the ScheduleManagement service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `ScheduleManagement` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `ScheduleManagement` service.
### Multi Tenant Architecture
The `ScheduleManagement` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `ScheduleManagement` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `ScheduleManagement` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `ScheduleManagement` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `ScheduleManagement` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
ScheduleManagement service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### ShiftTemplate resource
*Resource Definition* : Template for recurring or standard shift patterns. Owned by company. Used to quickly schedule repeatable work shifts; optionally scoped to a department.
*ShiftTemplate Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **name** | String | | | *Display name for the template (e.g., 'Morning Shift').* |
| **description** | Text | | | *Description/purpose of the shift template.* |
| **startTime** | String | | | *Template start time in HH:mm format.* |
| **endTime** | String | | | *Template end time in HH:mm format.* |
| **recurrenceRule** | String | | | *RFC 5545 RRULE-formatted string describing recurrence (e.g., weekly, biweekly).* |
| **departmentId** | ID | | | *Restricts applicability of template to a department if set.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
### Shift resource
*Resource Definition* : A scheduled shift for a company. Defines date, time span, location, and assignment to users/departments. Core entity for workforce operations.
*Shift Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **shiftDate** | Date | | | *Date of shift (YYYY-MM-DD).* |
| **startTime** | String | | | *Shift start time (HH:mm local time).* |
| **endTime** | String | | | *Shift end time (HH:mm local time).* |
| **location** | String | | | *Physical or logical location for the shift (if applicable).* |
| **departmentId** | ID | | | *Limits or indicates department responsible for this shift.* |
| **assignedUserIds** | ID | | | *User IDs assigned to the shift.* |
| **assignedDepartmentIds** | ID | | | *Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned.* |
| **status** | Enum | | | *Status of the shift (scheduled, completed, cancelled).* |
| **createdBy** | ID | | | *User who created the shift.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### status Enum Property
*Property Definition* : Status of the shift (scheduled, completed, cancelled).*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **scheduled** | `"scheduled""` | 0 |
| **completed** | `"completed""` | 1 |
| **cancelled** | `"cancelled""` | 2 |
## Business Api
### `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**
```js
axios({
method: 'POST',
url: '/v1/shifttemplates',
data: {
name:"String",
description:"Text",
startTime:"String",
endTime:"String",
recurrenceRule:"String",
departmentId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'PATCH',
url: `/v1/shifttemplates/${shiftTemplateId}`,
data: {
name:"String",
description:"Text",
startTime:"String",
endTime:"String",
recurrenceRule:"String",
departmentId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/shifttemplates/${shiftTemplateId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/shifttemplates/${shiftTemplateId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?name=&name=`
- Null: `?name=null`
**departmentId** (`ID`): Restricts applicability of template to a department if set.
- Single: `?departmentId=`
- Multiple: `?departmentId=&departmentId=`
- Null: `?departmentId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/shifttemplates**
```js
axios({
method: 'GET',
url: '/v1/shifttemplates',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// name: '' // Filter by name
// departmentId: '' // Filter by departmentId
}
});
```
**REST Response**
```json
{
"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**
```js
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**
```json
{
"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**
```js
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**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/shifts/${shiftId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/shifts/${shiftId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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-`, `$lin-`
- Null: `?shiftDate=null`
**departmentId** (`ID`): Limits or indicates department responsible for this shift.
- Single: `?departmentId=`
- Multiple: `?departmentId=&departmentId=`
- Null: `?departmentId=null`
**assignedUserIds** (`ID` array): User IDs assigned to the shift.
- Single: `?assignedUserIds=`
- Multiple: `?assignedUserIds=&assignedUserIds=`
- Null: `?assignedUserIds=null`
- Array contains: `?assignedUserIds=&assignedUserIds_op=contains` (default)
- Array overlap: `?assignedUserIds=&assignedUserIds=&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=`
- Multiple: `?assignedUserIds_op=&assignedUserIds_op=`
- Null: `?assignedUserIds_op=null`
**assignedDepartmentIds** (`ID` array): Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned.
- Single: `?assignedDepartmentIds=`
- Multiple: `?assignedDepartmentIds=&assignedDepartmentIds=`
- Null: `?assignedDepartmentIds=null`
- Array contains: `?assignedDepartmentIds=&assignedDepartmentIds_op=contains` (default)
- Array overlap: `?assignedDepartmentIds=&assignedDepartmentIds=&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=`
- Multiple: `?assignedDepartmentIds_op=&assignedDepartmentIds_op=`
- Null: `?assignedDepartmentIds_op=null`
**status** (`Enum`): Status of the shift (scheduled, completed, cancelled).
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/shifts**
```js
axios({
method: 'GET',
url: '/v1/shifts',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// shiftDate: '' // Filter by shiftDate
// departmentId: '' // Filter by departmentId
// assignedUserIds: '' // Filter by assignedUserIds
// assignedUserIds_op: '' // Filter by assignedUserIds_op
// assignedDepartmentIds: '' // Filter by assignedDepartmentIds
// assignedDepartmentIds_op: '' // Filter by assignedDepartmentIds_op
// status: '' // Filter by status
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "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": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-attendancemanagement-service
**Version:** `1.0.5`
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.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the AttendanceManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AttendanceManagement Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the AttendanceManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying AttendanceManagement objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the AttendanceManagement Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the AttendanceManagement service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the AttendanceManagement service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the AttendanceManagement service.
This service is configured to listen for HTTP requests on port `3002`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/attendancemanagement-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/attendancemanagement-api`
* **Production:** `https://workforceos.mindbricks.co/attendancemanagement-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the AttendanceManagement service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `AttendanceManagement` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `AttendanceManagement` service.
### Multi Tenant Architecture
The `AttendanceManagement` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `AttendanceManagement` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `AttendanceManagement` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `AttendanceManagement` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `AttendanceManagement` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
AttendanceManagement service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### AttendanceRecord resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **userId** | ID | | | *Referenced user (employee)* |
| **shiftId** | ID | | | *Related shift* |
| **checkInTime** | Date | | | *User check-in timestamp (set on check-in)* |
| **checkOutTime** | Date | | | *User check-out timestamp (set on check-out)* |
| **status** | Enum | | | *Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out)* |
| **lateByMinutes** | Integer | | | *How many minutes late (if late)* |
| **absenceReason** | String | | | *Reason for absence (manager-provided, e.g., sick, leave)* |
| **managerNote** | Text | | | *Manager/admin note (optional for manual absence management)* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### status Enum Property
*Property Definition* : Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out)*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **pending** | `"pending""` | 0 |
| **present** | `"present""` | 1 |
| **absent** | `"absent""` | 2 |
| **late** | `"late""` | 3 |
| **leftEarly** | `"leftEarly""` | 4 |
## Business Api
### `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**
```js
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**
```json
{
"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**
```js
axios({
method: 'POST',
url: '/v1/check-out',
data: {
attendanceRecordId:"ID",
checkOutTime:"Date",
status:"Enum",
lateByMinutes:"Integer",
absenceReason:"String",
managerNote:"Text",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
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**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/attendance-records/${attendanceRecordId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**shiftId** (`ID`): Related shift
- Single: `?shiftId=`
- Multiple: `?shiftId=&shiftId=`
- Null: `?shiftId=null`
**status** (`Enum`): Attendance status: present, absent, late, leftEarly, pending (checked in, not yet out)
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/attendance-records**
```js
axios({
method: 'GET',
url: '/v1/attendance-records',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// shiftId: '' // Filter by shiftId
// status: '' // Filter by status
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "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": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-taskmanagement-service
**Version:** `1.0.82`
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..
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the TaskManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our TaskManagement Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the TaskManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying TaskManagement objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the TaskManagement Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the TaskManagement service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the TaskManagement service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the TaskManagement service.
This service is configured to listen for HTTP requests on port `3004`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/taskmanagement-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/taskmanagement-api`
* **Production:** `https://workforceos.mindbricks.co/taskmanagement-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the TaskManagement service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `TaskManagement` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `TaskManagement` service.
### Multi Tenant Architecture
The `TaskManagement` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `TaskManagement` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `TaskManagement` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `TaskManagement` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `TaskManagement` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
TaskManagement service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### TaskAssignment resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **title** | String | | | *Task title visible to all assignees* |
| **description** | Text | | | *Detailed task description* |
| **dueTime** | Date | | | *Deadline for task completion* |
| **status** | Enum | | | *Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment)* |
| **assignerId** | ID | | | *User who created this task assignment* |
| **assigneeUserIds** | ID | | | *Direct user assignments - these users will receive individual tasks* |
| **assignedDepartmentIds** | ID | | | *Department assignments - all users in these departments will receive individual tasks* |
| **shiftId** | ID | | | *Optional shift link for the task* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### status Enum Property
*Property Definition* : Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment)*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **active** | `"active""` | 0 |
| **cancelled** | `"cancelled""` | 1 |
| **completed** | `"completed""` | 2 |
### IndividualTask resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **taskAssignmentId** | ID | | | *Reference to the parent task assignment* |
| **assigneeUserId** | ID | | | *The employee who receives this individual task* |
| **title** | String | | | *Task title (copied from parent assignment)* |
| **description** | Text | | | *Task description (copied from parent assignment)* |
| **status** | Enum | | | *Individual task status: pending, completed, or cancelled* |
| **completedTime** | Date | | | *When this employee completed their task* |
| **dueTime** | Date | | | *Deadline for completion (copied from parent)* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### status Enum Property
*Property Definition* : Individual task status: pending, completed, or cancelled*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **pending** | `"pending""` | 0 |
| **completed** | `"completed""` | 1 |
| **cancelled** | `"cancelled""` | 2 |
## Business Api
### `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**
```js
axios({
method: 'POST',
url: '/v1/taskassignments',
data: {
title:"String",
description:"Text",
dueTime:"Date",
status:"Enum",
assigneeUserIds:"ID",
assignedDepartmentIds:"ID",
shiftId:"ID",
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?taskAssignmentId=&taskAssignmentId=`
- Null: `?taskAssignmentId=null`
**assigneeUserId** (`ID`): The employee who receives this individual task
- Single: `?assigneeUserId=`
- Multiple: `?assigneeUserId=&assigneeUserId=`
- Null: `?assigneeUserId=null`
**status** (`Enum`): Individual task status: pending, completed, or cancelled
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- 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-`, `$lin-`
- Null: `?dueTime=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/myindividualtasks**
```js
axios({
method: 'GET',
url: '/v1/myindividualtasks',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// taskAssignmentId: '' // Filter by taskAssignmentId
// assigneeUserId: '' // Filter by assigneeUserId
// status: '' // Filter by status
// dueTime: '' // Filter by dueTime
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/taskassignmentwithprogress/${taskAssignmentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/myindividualtask/${individualTaskId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?title=&title=`
- 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-`, `$lin-`
- Null: `?dueTime=null`
**status** (`Enum`): Assignment status: active (distributing to employees) or cancelled (admin cancelled the whole assignment)
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**assignerId** (`ID`): User who created this task assignment
- Single: `?assignerId=`
- Multiple: `?assignerId=&assignerId=`
- Null: `?assignerId=null`
**assigneeUserIds** (`ID` array): Direct user assignments - these users will receive individual tasks
- Single: `?assigneeUserIds=`
- Multiple: `?assigneeUserIds=&assigneeUserIds=`
- Null: `?assigneeUserIds=null`
- Array contains: `?assigneeUserIds=&assigneeUserIds_op=contains` (default)
- Array overlap: `?assigneeUserIds=&assigneeUserIds=&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=`
- Multiple: `?assigneeUserIds_op=&assigneeUserIds_op=`
- Null: `?assigneeUserIds_op=null`
**assignedDepartmentIds** (`ID` array): Department assignments - all users in these departments will receive individual tasks
- Single: `?assignedDepartmentIds=`
- Multiple: `?assignedDepartmentIds=&assignedDepartmentIds=`
- Null: `?assignedDepartmentIds=null`
- Array contains: `?assignedDepartmentIds=&assignedDepartmentIds_op=contains` (default)
- Array overlap: `?assignedDepartmentIds=&assignedDepartmentIds=&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=`
- Multiple: `?assignedDepartmentIds_op=&assignedDepartmentIds_op=`
- Null: `?assignedDepartmentIds_op=null`
**shiftId** (`ID`): Optional shift link for the task
- Single: `?shiftId=`
- Multiple: `?shiftId=&shiftId=`
- Null: `?shiftId=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/taskassignments**
```js
axios({
method: 'GET',
url: '/v1/taskassignments',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// title: '' // Filter by title
// dueTime: '' // Filter by dueTime
// status: '' // Filter by status
// assignerId: '' // Filter by assignerId
// assigneeUserIds: '' // Filter by assigneeUserIds
// assigneeUserIds_op: '' // Filter by assigneeUserIds_op
// assignedDepartmentIds: '' // Filter by assignedDepartmentIds
// assignedDepartmentIds_op: '' // Filter by assignedDepartmentIds_op
// shiftId: '' // Filter by shiftId
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/taskassignments/${taskAssignmentId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'PATCH',
url: `/v1/individualtasks/${individualTaskId}`,
data: {
title:"String",
description:"Text",
status:"Enum",
dueTime:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
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**
```json
{
"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**
```js
axios({
method: 'POST',
url: '/v1/individualtasks',
data: {
taskAssignmentId:"ID",
assigneeUserId:"ID",
title:"String",
description:"Text",
status:"Enum",
completedTime:"Date",
dueTime:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/individualtasks/${individualTaskId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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"
}
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-leavemanagement-service
**Version:** `1.0.23`
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.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the LeaveManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our LeaveManagement Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the LeaveManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying LeaveManagement objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the LeaveManagement Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the LeaveManagement service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the LeaveManagement service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the LeaveManagement service.
This service is configured to listen for HTTP requests on port `3002`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/leavemanagement-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/leavemanagement-api`
* **Production:** `https://workforceos.mindbricks.co/leavemanagement-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the LeaveManagement service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `LeaveManagement` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `LeaveManagement` service.
### Multi Tenant Architecture
The `LeaveManagement` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `LeaveManagement` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `LeaveManagement` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `LeaveManagement` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `LeaveManagement` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
LeaveManagement service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### LeaveRequest resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **userId** | ID | | | *ID of employee/user requesting leave (auth:user.id)* |
| **departmentId** | ID | | | *Department (userGroup) id, for scoping leave if relevant* |
| **requestDate** | Date | | | *Datetime when leave requested* |
| **leaveType** | String | | | *Type of leave (e.g. vacation, sick, emergency).* |
| **startDate** | Date | | | *First day of leave (inclusive).* |
| **endDate** | Date | | | *Last day of leave (inclusive).* |
| **reason** | String | | | *Employee-provided reason/message for leave request* |
| **status** | Enum | | | *Leave request status (pending, approved, rejected, cancelled).* |
| **approverId** | ID | | | *UserId of manager/admin who approved/rejected/cancelled the request* |
| **approvedDate** | Date | | | *Date/time leave was approved/rejected/cancelled, if applicable.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### status Enum Property
*Property Definition* : Leave request status (pending, approved, rejected, cancelled).*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **pending** | `"pending""` | 0 |
| **approved** | `"approved""` | 1 |
| **rejected** | `"rejected""` | 2 |
| **cancelled** | `"cancelled""` | 3 |
## Business Api
### `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**
```js
axios({
method: 'POST',
url: '/v1/leaverequests',
data: {
departmentId:"ID",
leaveType:"String",
startDate:"Date",
endDate:"Date",
reason:"String",
approverId:"ID",
approvedDate:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
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**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/leaverequests/${leaveRequestId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'GET',
url: `/v1/leaverequests/${leaveRequestId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**departmentId** (`ID`): Department (userGroup) id, for scoping leave if relevant
- Single: `?departmentId=`
- Multiple: `?departmentId=&departmentId=`
- Null: `?departmentId=null`
**leaveType** (`String`): Type of leave (e.g. vacation, sick, emergency).
- Single (partial match, case-insensitive): `?leaveType=`
- Multiple: `?leaveType=&leaveType=`
- 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-`, `$lin-`
- 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-`, `$lin-`
- Null: `?endDate=null`
**status** (`Enum`): Leave request status (pending, approved, rejected, cancelled).
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/leaverequests**
```js
axios({
method: 'GET',
url: '/v1/leaverequests',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// departmentId: '' // Filter by departmentId
// leaveType: '' // Filter by leaveType
// startDate: '' // Filter by startDate
// endDate: '' // Filter by endDate
// status: '' // Filter by status
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "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=`
- Multiple: `?userId=&userId=`
- Null: `?userId=null`
**departmentId** (`ID`): Department (userGroup) id, for scoping leave if relevant
- Single: `?departmentId=`
- Multiple: `?departmentId=&departmentId=`
- Null: `?departmentId=null`
**leaveType** (`String`): Type of leave (e.g. vacation, sick, emergency).
- Single (partial match, case-insensitive): `?leaveType=`
- Multiple: `?leaveType=&leaveType=`
- 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-`, `$lin-`
- 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-`, `$lin-`
- Null: `?endDate=null`
**status** (`Enum`): Leave request status (pending, approved, rejected, cancelled).
- Single: `?status=` (case-insensitive)
- Multiple: `?status=&status=`
- Null: `?status=null`
**REST Request**
To access the api you can use the **REST** controller with the path **GET /v1/myleaverequests**
```js
axios({
method: 'GET',
url: '/v1/myleaverequests',
data: {
},
params: {
// Filter parameters (see Filter Parameters section above)
// userId: '' // Filter by userId
// departmentId: '' // Filter by departmentId
// leaveType: '' // Filter by leaveType
// startDate: '' // Filter by startDate
// endDate: '' // Filter by endDate
// status: '' // Filter by status
}
});
```
**REST Response**
```json
{
"status": "OK",
"statusCode": "200",
"elapsedMs": 126,
"ssoTime": 120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName": "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**
```js
axios({
method: 'GET',
url: `/v1/myleaverequest/${leaveRequestId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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"
}
}
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-payrollreporting-service
**Version:** `1.0.9`
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.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the PayrollReporting Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our PayrollReporting Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the PayrollReporting Service via HTTP requests for purposes such as creating, updating, deleting and querying PayrollReporting objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the PayrollReporting Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the PayrollReporting service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the PayrollReporting service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the PayrollReporting service.
This service is configured to listen for HTTP requests on port `3006`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/payrollreporting-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/payrollreporting-api`
* **Production:** `https://workforceos.mindbricks.co/payrollreporting-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the PayrollReporting service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `PayrollReporting` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `PayrollReporting` service.
### Multi Tenant Architecture
The `PayrollReporting` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `PayrollReporting` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `PayrollReporting` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `PayrollReporting` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `PayrollReporting` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
PayrollReporting service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### PayrollReport resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **userId** | ID | | | *Reference to the user/employee this report summarizes (auth:user.id).* |
| **periodStart** | Date | | | *Start date of reporting/payroll period (inclusive).* |
| **periodEnd** | Date | | | *End date of the reporting/payroll period (inclusive).* |
| **totalHoursWorked** | Double | | | *Total hours worked during this period (summed from attendance data, auto-calculated).* |
| **overtimeHours** | Double | | | *Total overtime hours for period (auto-calculated from attendance, company policy).* |
| **absenceDays** | Integer | | | *Total days absent during period (from leave & attendance). Auto-calculated.* |
| **bonus** | Double | | | *Manual bonus to add for this period (optional entry by admin/manager only).* |
| **deduction** | Double | | | *Manual deduction for this period (optional entry by admin/manager only).* |
| **salaryCalculated** | Double | | | *Auto-calculated salary for the period: base salary, hours, overtime, bonuses, and deductions. Always calculated, never direct entry.* |
| **paymentStatus** | Enum | | | *Manual entry tracking payment status for this period ('paid', 'unpaid', 'partial', 'pending').* |
| **paymentDate** | Date | | | *Manual entry of actual date payment was made for this period (optional, admins/managers only).* |
| **notes** | String | | | *Optional notes (manual, internal)—remark/history on payment changes, bonuses, or irregularities.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### paymentStatus Enum Property
*Property Definition* : Manual entry tracking payment status for this period ('paid', 'unpaid', 'partial', 'pending').*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **paid** | `"paid""` | 0 |
| **unpaid** | `"unpaid""` | 1 |
| **partial** | `"partial""` | 2 |
| **pending** | `"pending""` | 3 |
## Business Api
### `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**
```js
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.
```json
{
"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**
```js
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.
```json
{
"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**
```js
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.
```json
{
"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**
```js
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.
```json
{
"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": []
}
```
### Authentication Specific Routes
### Common Routes
### Route: currentuser
*Route Definition*: Retrieves the currently authenticated user's session information.
*Route Type*: sessionInfo
*Access Route*: `GET /currentuser`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Returns the authenticated session object associated with the current access token.
- If no valid session exists, responds with a 401 Unauthorized.
```js
// Sample GET /currentuser call
axios.get("/currentuser", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns the session object, including user-related data and token information.
````
{
"sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
"userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"email": "user@example.com",
"fullname": "John Doe",
"roleId": "user",
"tenantId": "abc123",
"accessToken": "jwt-token-string",
...
}
````
**Error Response**
**401 Unauthorized:** No active session found.
````
{
"status": "ERR",
"message": "No login found"
}
````
**Notes**
* This route is typically used by frontend or mobile applications to fetch the current session state after login.
* The returned session includes key user identity fields, tenant information (if applicable), and the access token for further authenticated requests.
* Always ensure a valid access token is provided in the request to retrieve the session.
### Route: permissions
`*Route Definition*`: Retrieves all effective permission records assigned to the currently authenticated user.
`*Route Type*`: permissionFetch
*Access Route*: `GET /permissions`
#### Parameters
This route does **not** require any request parameters.
#### Behavior
- Fetches all active permission records (`givenPermissions` entries) associated with the current user session.
- Returns a full array of permission objects.
- Requires a valid session (`access token`) to be available.
```js
// Sample GET /permissions call
axios.get("/permissions", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
Returns an array of permission objects.
```json
[
{
"id": "perm1",
"permissionName": "adminPanel.access",
"roleId": "admin",
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
},
{
"id": "perm2",
"permissionName": "orders.manage",
"roleId": null,
"subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
"subjectUserGroupId": null,
"objectId": null,
"canDo": true,
"tenantCodename": "store123"
}
]
````
Each object reflects a single permission grant, aligned with the givenPermissions model:
- `**permissionName**`: The permission the user has.
- `**roleId**`: If the permission was granted through a role.
-` **subjectUserId**`: If directly granted to the user.
- `**subjectUserGroupId**`: If granted through a group.
- `**objectId**`: If tied to a specific object (OBAC).
- `**canDo**`: True or false flag to represent if permission is active or restricted.
**Error Responses**
* **401 Unauthorized**: No active session found.
```json
{
"status": "ERR",
"message": "No login found"
}
````
* **500 Internal Server Error**: Unexpected error fetching permissions.
**Notes**
* The /permissions route is available across all backend services generated by Mindbricks, not just the auth service.
* Auth service: Fetches permissions freshly from the live database (givenPermissions table).
* Other services: Typically use a cached or projected view of permissions stored in a common ElasticSearch store, optimized for faster authorization checks.
> **Tip**:
> Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.
### Route: permissions/:permissionName
*Route Definition*: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.
*Route Type*: permissionScopeCheck
*Access Route*: `GET /permissions/:permissionName`
#### Parameters
| Parameter | Type | Required | Population |
|------------------|--------|----------|------------------------|
| permissionName | String | Yes | `request.params.permissionName` |
#### Behavior
- Evaluates whether the current user **has access** to the given `permissionName`.
- Returns a structured object indicating:
- Whether the permission is generally granted (`canDo`)
- Which object IDs are explicitly included or excluded from access (`exceptions`)
- Requires a valid session (`access token`).
```js
// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
headers: {
"Authorization": "Bearer your-jwt-token"
}
});
````
**Success Response**
```json
{
"canDo": true,
"exceptions": [
"a1f2e3d4-xxxx-yyyy-zzzz-object1",
"b2c3d4e5-xxxx-yyyy-zzzz-object2"
]
}
````
* If `canDo` is `true`, the user generally has the permission, but not for the objects listed in `exceptions` (i.e., restrictions).
* If `canDo` is `false`, the user does not have the permission by default — but only for the objects in `exceptions`, they do have permission (i.e., selective overrides).
* The exceptions array contains valid **UUID strings**, each corresponding to an object ID (typically from the data model targeted by the permission).
## Copyright
All sources, documents and other digital materials are copyright of .
## About Us
For more information please visit our website: .
.
.
---
# REST API GUIDE
## workforceos-announcementmanagement-service
**Version:** `1.0.10`
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.
## Architectural Design Credit and Contact Information
The architectural design of this microservice is credited to .
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:
Email:
We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.
## Documentation Scope
Welcome to the official documentation for the AnnouncementManagement Service's REST API. This document is designed to provide a comprehensive guide to interfacing with our AnnouncementManagement Service exclusively through RESTful API endpoints.
**Intended Audience**
This documentation is intended for developers and integrators who are looking to interact with the AnnouncementManagement Service via HTTP requests for purposes such as creating, updating, deleting and querying AnnouncementManagement objects.
**Overview**
Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.
Beyond REST
It's important to note that the AnnouncementManagement Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.
## Authentication And Authorization
To ensure secure access to the AnnouncementManagement service's protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it's important to note that access control varies across different routes:
**Protected API**:
Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.
**Public API **:
The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.
### Token Locations
When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.
| Location | Token Name / Param Name |
| ---------------------- | ---------------------------- |
| Query | access_token |
| Authorization Header | Bearer |
| Header | workforceos-access-token|
| Header | workforceos-access-token-{companyCodename}|
| Cookie | workforceos-access-token-{companyCodename}|
Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.
## Api Definitions
This section outlines the API endpoints available within the AnnouncementManagement service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It's important to understand the flexibility in how parameters can be included in requests to effectively interact with the AnnouncementManagement service.
This service is configured to listen for HTTP requests on port `3022`,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
* **API Test Interface (API Face):** `/`
* **Swagger Documentation:** `/swagger`
* **Postman Collection Download:** `/getPostmanCollection`
* **Health Checks:** `/health` and `/admin/health`
* **Current Session Info:** `/currentuser`
* **Favicon:** `/favicon.ico`
This service is accessible via the following environment-specific URLs:
* **Preview:** `https://workforceos.prw.mindbricks.com/announcementmanagement-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/announcementmanagement-api`
* **Production:** `https://workforceos.mindbricks.co/announcementmanagement-api`
**Parameter Inclusion Methods:**
Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:
**Query Parameters:** Included directly in the URL's query string.
**Path Parameters:** Embedded within the URL's path.
**Body Parameters:** Sent within the JSON body of the request.
**Session Parameters:** Automatically read from the session object. This method is used for parameters that are intrinsic to the user's session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.
**Note on Session Parameters:**
Session parameters represent a unique method of parameter inclusion, relying on the context of the user's session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.
By adhering to the specified parameter inclusion methods, you can effectively utilize the AnnouncementManagement service's API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.
### Common Parameters
The `AnnouncementManagement` service's business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.
### Supported Common Parameters:
- **getJoins (BOOLEAN)**: Controls whether to retrieve associated objects along with the main object. By default, `getJoins` is assumed to be `true`. Set it to `false` if you prefer to receive only the main fields of an object, excluding its associations.
- **excludeCQRS (BOOLEAN)**: Applicable only when `getJoins` is `true`. By default, `excludeCQRS` is set to `false`. Enabling this parameter (`true`) omits non-local associations, which are typically more resource-intensive as they require querying external services like ElasticSearch for additional information. Use this to optimize response times and resource usage.
- **requestId (String)**: Identifies a request to enable tracking through the service's log chain. A random hex string of 32 characters is assigned by default. If you wish to use a custom `requestId`, simply include it in your query parameters.
- **caching (BOOLEAN)**: Determines the use of caching for query API. By default, caching is enabled (`true`). To ensure the freshest data directly from the database, set this parameter to `false`, bypassing the cache.
- **cacheTTL (Integer)**: Specifies the Time-To-Live (TTL) for query caching, in seconds. This is particularly useful for adjusting the default caching duration (5 minutes) for `get list` queries. Setting a custom `cacheTTL` allows you to fine-tune the cache lifespan to meet your needs.
- **pageNumber (Integer)**: For paginated `get list` API's, this parameter selects which page of results to retrieve. The default is `1`, indicating the first page. To disable pagination and retrieve all results, set `pageNumber` to `0`.
- **pageRowCount (Integer)**: In conjunction with paginated API's, this parameter defines the number of records per page. The default value is `25`. Adjusting `pageRowCount` allows you to control the volume of data returned in a single request.
By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the `AnnouncementManagement` service.
### Multi Tenant Architecture
The `AnnouncementManagement` service operates within a multi tenant architecture.
The service is designed to support multiple tenants, each with its distinct data and configuration. This architecture ensures that data is securely isolated between tenants, preventing unauthorized access and maintaining data integrity.
The service tenant is called `company` and identified as `companyId`.
Other than platform users like superAdmin, saasAdmin and saasUser that belong to the root tenant, the tenant creators(owners) and users will all be associated with an company tenant.
When users login their scope will be isolated only to include one tenant data they below. So user may acces only this logined tennat through out the session. After loging in to e specific tenant, users should include the tenant id in their request to access the tenant data. In each request they may access different tenant data if they belong them.
#### Key Points:
- **Tenant-Specific Requests**: It is imperative that each request specifies the tenant it pertains to. This is crucial because most API's are designed to interact exclusively with objects that are part of the specified tenant sandbox.
- **User Distinction**: The requesting user must have a registration for that tenant. The service searches for a `company` specific token (cookie or bearer) using the provided `company`Id in the request header. Note that to be able to login and use multiple tenant's sites a user must register for them all.
- **Request Header Parameter**: When making a request, include the desired `companyId` in the request header using the parameter name ``. This signals to the service which domain context to apply for the request processing. Alternatively, you can include the tenant id in the query parameters with the name `companyId`.
- **Root Tenant**: As all multi tenant architectures this application also has a default root tenant which created automatically. If there is no tenant mark for the request, the request are assumed as to the root tenant. Root tenant is also the hub for registering tenant creating and their owner users. When users register themselves in the root tenant, an (company) will alos be created with the given data in the request body and the user will be asssociated with this new tenant record as the `tenantAdmin`.
- **Superadmin account**: A super admin account is created with the given credentials in the design so that there is an absolute user which has all rights in the root tenant and other tenants. This account is used to create and manage all other tenants in the system.
- **Tenant Registration**: The `AnnouncementManagement` service allows for the registration of new tenants. Any user who registers himself in the root tenant through the POST /tenantowners , can create a new company publicly with the user registration. The creator user of the company record will be registred to the new tenenat with the `tenantAdmin` role.
#### Implementation:
When the user logins there may be few ways for Mindbricks to recognize and set the tenant id in the session.
1. Mindbricks will check the url of the login request if it matches tenant url.
2. Mindbricks will check the `` has the tenant id.
3. Mindbricks will check if the user is associated with a `company` in the data model.
After you login a tenant successfully, ensure that your requests accurately target objects that fall within the tenant scope set during the login session.
Ensure your requests are correctly formatted to include the domain sandbox information in the header. This enables the `AnnouncementManagement` service to accurately identify the domain context, facilitating proper access control and data management based on the user's permissions and the specified domain.
```js
axios({
method: 'GET',
headers: {
'': 'Your-companyId-here'
}
url: "/someroutepath",
data: {
"someData":"someData"
},
params: {
"aParam":"aParam"
}
});
````
By adhering to this domain sandbox model, the `AnnouncementManagement` service maintains a secure and organized structure for handling requests across different domains, ensuring that operations are performed within the correct contextual boundaries.
### Error Response
If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:
- **400 Bad Request**: The request was improperly formatted or contained invalid parameters, preventing the server from processing it.
- **401 Unauthorized**: The request lacked valid authentication credentials or the credentials provided do not grant access to the requested resource.
- **404 Not Found**: The requested resource was not found on the server.
- **500 Internal Server Error**: The server encountered an unexpected condition that prevented it from fulfilling the request.
Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.
```js
{
"result": "ERR",
"status": 400,
"message": "errMsg_organizationIdisNotAValidID",
"errCode": 400,
"date": "2024-03-19T12:13:54.124Z",
"detail": "String"
}
````
### Object Structure of a Successfull Response
When the `AnnouncementManagement` service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.
**Key Characteristics of the Response Envelope:**
- **Data Presentation**: Depending on the nature of the request, the service returns either a single data object or an array of objects encapsulated within the JSON envelope.
- **Creation and Update API**: These API routes return the unmodified (pure) form of the data object(s), without any associations to other data objects.
- **Delete API**: Even though the data is removed from the database, the last known state of the data object(s) is returned in its pure form.
- **Get Requests**: A single data object is returned in JSON format.
- **Get List Requests**: An array of data objects is provided, reflecting a collection of resources.
- **Data Structure and Joins**: The complexity of the data structure in the response can vary based on the API's architectural design and the join options specified in the request. The architecture might inherently limit join operations, or they might be dynamically controlled through query parameters.
- **Pure Data Forms**: In some cases, the response mirrors the exact structure found in the primary data table, without extensions.
- **Extended Data Forms**: Alternatively, responses might include data extended through joins with tables within the same service or aggregated from external sources, such as ElasticSearch indices related to other services.
- **Join Varieties**: The extensions might involve one-to-one joins, resulting in single object associations, or one-to-many joins, leading to an array of objects. In certain instances, the data might even feature nested inclusions from other data objects.
**Design Considerations**: The structure of a API's response data is meticulously crafted during the service's architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.
**Brief Data**: Certain API's return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.
### API Response Structure
The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.
**HTTP Status Codes:**
- **200 OK**: This status code is returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request has been processed successfully.
- **201 Created**: This status code is specific to CREATE operations, signifying that the requested resource has been successfully created.
**Success Response Format:**
For successful operations, the response includes a `"status": "OK"` property, signaling the successful execution of the request. The structure of a successful response is outlined below:
```json
{
"status":"OK",
"statusCode": 200,
"elapsedMs":126,
"ssoTime":120,
"source": "db",
"cacheKey": "hexCode",
"userId": "ID",
"sessionId": "ID",
"requestId": "ID",
"dataName":"products",
"method":"GET",
"action":"list",
"appVersion":"Version",
"rowCount":3
"products":[{},{},{}],
"paging": {
"pageNumber":1,
"pageRowCount":25,
"totalRowCount":3,
"pageCount":1
},
"filters": [],
"uiPermissions": []
}
````
- **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation performed.
**Handling Errors:**
For details on handling error scenarios and understanding the structure of error responses, please refer to the "Error Response" section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.
## Resources
AnnouncementManagement service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.
### Announcement resource
*Resource Definition* : 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 Resource Properties*
| Name | Type | Required | Default | Definition |
| ---- | ---- | -------- | ------- | ---------- |
| **creatorId** | ID | | | *auth:user.id - Creator of the announcement* |
| **title** | String | | | *Announcement subject/title (short display name).* |
| **body** | Text | | | *Announcement content body (markdown/HTML string).* |
| **targetDepartmentIds** | ID | | | *Department userGroup IDs (auth:userGroup.id) to target recipients. Null/empty means all departments. Used for scoping announcements to groups.* |
| **audienceUserIds** | ID | | | *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 | | | *Scheduled send time for the announcement (UTC). Immediate if now/past, future means scheduled/pending delivery. Used for status logic.* |
| **visibleUntil** | Date | | | *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 | | | *Announcement status: scheduled (future, unsent); sent (visible/delivered); cancelled (withdrawn by admin/manager); status changes control delivery/event publishing.* |
| **companyId** | ID | | | *An ID value to represent the tenant id of the company* |
#### Enum Properties
Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.
##### status Enum Property
*Property Definition* : Announcement status: scheduled (future, unsent); sent (visible/delivered); cancelled (withdrawn by admin/manager); status changes control delivery/event publishing.*Enum Options*
| Name | Value | Index |
| ---- | ----- | ----- |
| **scheduled** | `"scheduled""` | 0 |
| **sent** | `"sent""` | 1 |
| **cancelled** | `"cancelled""` | 2 |
## Business Api
### `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**
```js
axios({
method: 'POST',
url: '/v1/announcements',
data: {
title:"String",
body:"Text",
targetDepartmentIds:"ID",
audienceUserIds:"ID",
sendTime:"Date",
visibleUntil:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'PATCH',
url: `/v1/announcements/${announcementId}`,
data: {
title:"String",
body:"Text",
targetDepartmentIds:"ID",
audienceUserIds:"ID",
sendTime:"Date",
visibleUntil:"Date",
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
axios({
method: 'DELETE',
url: `/v1/announcements/${announcementId}`,
data: {
},
params: {
}
});
```
**REST Response**
```json
{
"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**
```js
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.
```json
{
"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**
```js
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.
```json
{
"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=`
- Multiple: `?creatorId=&creatorId=`
- Null: `?creatorId=null`
**title** (`String`): Announcement subject/title (short display name).
- Single (partial match, case-insensitive): `?title=