REST API GUIDE

workforceos-aiworkforceanalytics-service

Version: 1.0.134

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.

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 AiWorkforceAnalytics Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our AiWorkforceAnalytics Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the AiWorkforceAnalytics Service via HTTP requests for purposes such as creating, updating, deleting and querying AiWorkforceAnalytics 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 AiWorkforceAnalytics 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 AiWorkforceAnalytics 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 AiWorkforceAnalytics 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 AiWorkforceAnalytics 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:

This service is accessible via the following environment-specific URLs:

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 AiWorkforceAnalytics 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 AiWorkforceAnalytics 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:

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 AiWorkforceAnalytics service.

Multi Tenant Architecture

The AiWorkforceAnalytics 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:

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 AiWorkforceAnalytics service to accurately identify the domain context, facilitating proper access control and data management based on the user’s permissions and the specified domain.
axios({
  method: 'GET',
  headers: {
    '': 'Your-companyId-here'
  }
  url: "/someroutepath",
  data: {
    "someData":"someData"
  },
  params: {
    "aParam":"aParam"
  }
});

By adhering to this domain sandbox model, the AiWorkforceAnalytics 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:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "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 AiWorkforceAnalytics 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:

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:

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:

{
  "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": []
}

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

AiWorkforceAnalytics 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.

AiInsight resource

Resource Definition : Represents an AI-generated insight, analytic, or tip for a company (and optionally individual user) for a specific period/type. Used for staffing recommendations, absenteeism patterns, productivity, and targeted advice. Stores computed detail as JSON and current delivery/processing status. AiInsight Resource Properties

Name Type Required Default Definition
insightType String Type/classification of the insight (e.g. 'staffingPrediction', 'absenteeismPattern', 'shiftAnomaly', 'productivityTip').
audienceUserId ID If present, insight is for a specific employee; otherwise company/manager-level.
applicablePeriod Object Date range period to which the insight applies (object: {startDate, endDate})
details Text JSON-stringified blob containing the AI result, message, chart data, or recommendation.
aiStatus Enum Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed).
deliveredTime Date Actual delivery/publication time (set when status becomes 'delivered'); null when pending.
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.

aiStatus Enum Property

Property Definition : Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed).Enum Options

Name Value Index
pending "pending"" 0
delivered "delivered"" 1
error "error"" 2

Business Api

Create Aiinsight API

[Default create API] — This is the designated default create API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations. Internal/system API to create a new AI insight record for a company and period (typically used by AI agents or cron jobs, not direct user input). Requires that company has an active AI subscription. Sets status to pending; downstream process delivers and updates status.

API Frontend Description By The Backend Architect

Not a user-facing API. Used by the platform for inserting new insight data for later dashboard/alert delivery.

Rest Route

The createAiInsight API REST controller can be triggered via the following route:

/v1/aiinsights

Rest Request Parameters

The createAiInsight api has got 6 regular request parameters

Parameter Type Required Population
insightType String true request.body?.[“insightType”]
audienceUserId ID false request.body?.[“audienceUserId”]
applicablePeriod Object true request.body?.[“applicablePeriod”]
details Text true request.body?.[“details”]
aiStatus Enum true request.body?.[“aiStatus”]
deliveredTime Date false request.body?.[“deliveredTime”]
insightType : Type/classification of the insight (e.g. ‘staffingPrediction’, ‘absenteeismPattern’, ‘shiftAnomaly’, ‘productivityTip’).
audienceUserId : If present, insight is for a specific employee; otherwise company/manager-level.
applicablePeriod : Date range period to which the insight applies (object: {startDate, endDate})
details : JSON-stringified blob containing the AI result, message, chart data, or recommendation.
aiStatus : Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed).
deliveredTime : Actual delivery/publication time (set when status becomes ‘delivered’); null when pending.

REST Request To access the api you can use the REST controller with the path POST /v1/aiinsights

  axios({
    method: 'POST',
    url: '/v1/aiinsights',
    data: {
            insightType:"String",  
            audienceUserId:"ID",  
            applicablePeriod:"Object",  
            details:"Text",  
            aiStatus:"Enum",  
            deliveredTime:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "aiInsight",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"aiInsight": {
		"id": "ID",
		"insightType": "String",
		"audienceUserId": "ID",
		"applicablePeriod": "Object",
		"details": "Text",
		"aiStatus": "Enum",
		"aiStatus_idx": "Integer",
		"deliveredTime": "Date",
		"companyId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Aiinsight API

[Default get API] — This is the designated default get API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a detailed AI insight for dashboards or notification rendering. Only accessible to: admin/manager of company, or employee for their tips (audienceUserId matches requester) AND company has active subscription.

API Frontend Description By The Backend Architect

FE must use this API to show a detailed AI insight. Employees may only see their own tips (if audienceUserId matches their userId), admin/managers may see all for their company.

Rest Route

The getAiInsight API REST controller can be triggered via the following route:

/v1/insights/:id

Rest Request Parameters

The getAiInsight api has got 2 regular request parameters

Parameter Type Required Population
aiInsightId ID true request.params?.[“aiInsightId”]
id String true request.params?.[“id”]
aiInsightId : This id paremeter is used to query the required data object.
id : This parameter will be used to select the data object that is queried

REST Request To access the api you can use the REST controller with the path GET /v1/insights/:id

  axios({
    method: 'GET',
    url: `/v1/insights/${id}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "aiInsight",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"aiInsight": {
		"audienceUser": {
			"email": "String",
			"fullname": "String",
			"avatar": "String"
		},
		"isActive": true
	}
}

List Aiinsights API

[Default list API] — This is the designated default list API for the aiInsight data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all accessible AI insights for dashboards or user tip listings, scoped by role and audienceUserId, and company subscription. Filter by type, status, period.

API Frontend Description By The Backend Architect

Use this API to build an AI insights dashboard for company (admin/manager: all insights; employee: only their own or broadcast tips). Use filters as appropriate for time/type/audience. UI must show no data if company is not subscribed.

Rest Route

The listAiInsights API REST controller can be triggered via the following route:

/v1/insights

Rest Request Parameters The listAiInsights api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/insights

  axios({
    method: 'GET',
    url: '/v1/insights',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "aiInsights",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"aiInsights": [
		{
			"audienceUser": [
				{
					"email": "String",
					"fullname": "String",
					"avatar": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Save Insight API

Saves an AI workforce insight from stream conversation to database for history tracking

Rest Route

The saveInsight API REST controller can be triggered via the following route:

/v1/saveinsight

Rest Request Parameters

The saveInsight api has got 13 regular request parameters

Parameter Type Required Population
title String true request.body?.[“title”]
summary String true request.body?.[“summary”]
insightType String true request.body?.[“insightType”]
audienceType String true request.body?.[“audienceType”]
chart Object false request.body?.[“chart”]
data Object false request.body?.[“data”]
suggestion String false request.body?.[“suggestion”]
period String false request.body?.[“period”]
audienceUserId String false request.body?.[“audienceUserId”]
applicablePeriod Object true request.body?.[“applicablePeriod”]
details Text true request.body?.[“details”]
aiStatus Enum true request.body?.[“aiStatus”]
deliveredTime Date false request.body?.[“deliveredTime”]
title : Insight title from AI stream
summary : Insight summary from AI stream
insightType : Type of insight (shift_optimization, absenteeism_alert, etc.)
audienceType : Target audience (admin, manager, employee, company)
chart : Optional chart data from AI
data : Additional data from AI insight
suggestion : AI suggestion/recommendation
period : Time period for the insight
audienceUserId : Specific user ID if personalized
applicablePeriod : Date range period to which the insight applies (object: {startDate, endDate})
details : JSON-stringified blob containing the AI result, message, chart data, or recommendation.
aiStatus : Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed).
deliveredTime : Actual delivery/publication time (set when status becomes ‘delivered’); null when pending.

REST Request To access the api you can use the REST controller with the path POST /v1/saveinsight

  axios({
    method: 'POST',
    url: '/v1/saveinsight',
    data: {
            title:"String",  
            summary:"String",  
            insightType:"String",  
            audienceType:"String",  
            chart:"Object",  
            data:"Object",  
            suggestion:"String",  
            period:"String",  
            audienceUserId:"String",  
            applicablePeriod:"Object",  
            details:"Text",  
            aiStatus:"Enum",  
            deliveredTime:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "aiInsight",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"aiInsight": {
		"id": "ID",
		"insightType": "String",
		"audienceUserId": "ID",
		"applicablePeriod": "Object",
		"details": "Text",
		"aiStatus": "Enum",
		"aiStatus_idx": "Integer",
		"deliveredTime": "Date",
		"companyId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Save Aiinsight API

Saves an AI workforce insight from stream conversation to database for history tracking

Rest Route

The saveAiInsight API REST controller can be triggered via the following route:

/v1/save-insight

Rest Request Parameters

The saveAiInsight api has got 1 regular request parameter

Parameter Type Required Population
insightType String false request.body?.[“insightType”]
insightType : Type of insight (auto-detected by AI agent)

REST Request To access the api you can use the REST controller with the path POST /v1/save-insight

  axios({
    method: 'POST',
    url: '/v1/save-insight',
    data: {
            insightType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "aiInsight",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"aiInsight": {
		"id": "ID",
		"insightType": "String",
		"audienceUserId": "ID",
		"applicablePeriod": "Object",
		"details": "Text",
		"aiStatus": "Enum",
		"aiStatus_idx": "Integer",
		"deliveredTime": "Date",
		"companyId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

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

// 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

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

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "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:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

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

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .