

# **WORKFORCEOS**

**FRONTEND GUIDE FOR AI CODING AGENTS - PART 14 - AiWorkforceAnalytics Service**

This document is a part of a REST API guide for the workforceos project.
It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of aiWorkforceAnalytics

## Service Access

AiWorkforceAnalytics service management is handled through service specific base urls.

AiWorkforceAnalytics  service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs.
The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the aiWorkforceAnalytics service, the base URLs are:

* **Preview:** `https://workforceos.prw.mindbricks.com/aiworkforceanalytics-api`
* **Staging:** `https://workforceos-stage.mindbricks.co/aiworkforceanalytics-api`
* **Production:** `https://workforceos.mindbricks.co/aiworkforceanalytics-api`

### Tenant URL Prefix and Header Forwarding

Tenant context is resolved by frontend routing strategy:
- preview/test: URL prefix `/{tenantCodename}` (example: `/babil/products`)
- production: tenant subdomain (example: `babil.appname...`)

Then backend API calls must always claim target tenant with header:

```js
headers["mbx-company-codename"] = tenantCodenameFromUrl;
```

URL prefix/subdomain is frontend-only tenant selection. Use header forwarding for all tenant-scoped calls to `aiWorkforceAnalytics` service.

## Scope

**AiWorkforceAnalytics Service Description**

Microservice for computing and delivering AI-powered workforce analytics (e.g., shift optimization, absenteeism insights, staffing trends) for eligible (subscribed) companies. Handles insight calculation, storage, and secure distribution to authorized users. Publishes insight alerts/events for notifications. Strictly enforces company data isolation and subscription gating on all features.

AiWorkforceAnalytics service provides apis and business logic for following data objects in workforceos application. 
Each data object may be either a central domain of the application data structure or a related helper data object for a central concept.
Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.  


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


## AiWorkforceAnalytics Service Frontend Description By The Backend Architect

# aiWorkforceAnalytics Service - FE Prompt

This service exposes APIs and (optionally) AI endpoints for accessing company-level and personal AI-powered workforce insights. All access is strictly RBAC and company-tenant isolated. Insights may be addressed to admins/managers (e.g., operational or team trends) or to employees (personal tips/alerts). For dashboards and widgets, use `listAiInsights` (with appropriate filters by period, type, or recipient), and for detail, use `getAiInsight`. 

Frontends must ensure they handle and display only those insights the authenticated user is authorized for (e.g., an employee sees only their tips/alerts by id, not company/department ones).


## API Structure

### Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

**HTTP Status Codes:**

* **200 OK**: Returned for successful GET, LIST, UPDATE, or DELETE operations, indicating that the request was processed successfully.
* **201 Created**: Returned for CREATE operations, indicating that the resource was created successfully.

**Success Response Format:**

For successful operations, the response includes a `"status": "OK"` property, signaling that the request executed successfully. The structure of a successful response is outlined below:

```json
{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}
```
* **`products`**: In this example, this key contains the actual response content, which may be a single object or an array of objects depending on the operation.

### Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

### Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

* **400 Bad Request**: The request was improperly formatted or contained invalid parameters.
* **401 Unauthorized**: The request lacked a valid authentication token; login is required.
* **403 Forbidden**: The current token does not grant access to the requested resource.
* **404 Not Found**: The requested resource was not found on the server.
* **500 Internal Server Error**: The server encountered an unexpected condition.

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

```js
{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}
```


## AiInsight Data Object

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

### AiInsight  Data Object Frontend Description By The Backend Architect

When presenting an aiInsight: show title (based on type), summary preview (from details), and period. For admins/managers, show all for their company; for employees, only those addressed to them (`audienceUserId`). Include a details view with interpretation of the insight data (e.g., charts if possible). DeliveredTime indicates when it was made available.


### AiInsight Data Object Properties

AiInsight data object has got following properties that are represented as table fields in the database scheme. 
These properties don't stand just for data storage, but each may have different settings to manage the business logic. 

| Property | Type | IsArray | Required | Secret | Description |
|----------|------|---------|----------|--------|-------------|
| `insightType` | String | false | Yes | No | Type/classification of the insight (e.g. 'staffingPrediction', 'absenteeismPattern', 'shiftAnomaly', 'productivityTip'). |
| `audienceUserId` | ID | false | No | No | If present, insight is for a specific employee; otherwise company/manager-level. |
| `applicablePeriod` | Object | false | Yes | No | Date range period to which the insight applies (object: {startDate, endDate}) |
| `details` | Text | false | Yes | No | JSON-stringified blob containing the AI result, message, chart data, or recommendation. |
| `aiStatus` | Enum | false | Yes | No | Status of the insight; pending (to deliver), delivered (published), error (AI-failed/delivery failed). |
| `deliveredTime` | Date | false | No | No | Actual delivery/publication time (set when status becomes 'delivered'); null when pending. |
| `companyId` | ID | false | Yes | No | An ID value to represent the tenant id of the company |
* Required properties are mandatory for creating objects and must be provided in the request body if no default value, formula or session bind is set.



### Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. 
The enum options value will be stored as strings in the database, 
but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option.
You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values.
In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

- **aiStatus**: [pending, delivered, error]


### Relation Properties

`audienceUserId`

Mindbricks supports relations between data objects, allowing you to define how objects are linked together.
The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search.
These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects.
If the relation points to another service, frontend should use the referenced service api in case it needs related data.
The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. 
In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that, 

1- instaead of these relational ids you show the main human readable field of the related target data (like name),
2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.


- **audienceUserId**: ID
Relation to `user`.id

The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.

Required: No


### Filter Properties

`insightType` `audienceUserId` `applicablePeriod` `aiStatus` `companyId`

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria.
These properties are automatically mapped as API parameters in the listing API's.

- **insightType**: String  has a filter named `insightType`

- **audienceUserId**: ID  has a filter named `audienceUserId`

- **applicablePeriod**: Object  has a filter named `applicablePeriod`

- **aiStatus**: Enum  has a filter named `aiStatus`

- **companyId**: ID  has a filter named `companyId`



## Default CRUD APIs

For each data object, the backend architect may designate **default APIs** for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (`isDefaultApi`), the frontend generator auto-discovers the most general API for each operation.

### AiInsight Default APIs

**Display Label Property:** `insightType` — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).
| Operation | API Name | Route | Explicitly Set |
|-----------|----------|-------|----------------|
| Create | `createAiInsight` | `/v1/aiinsights` | Yes |
| Update | `updateAiInsight` | `/v1/aiinsights/:aiInsightId` | Yes |
| Delete | _none_ | - | Auto |
| Get | `getAiInsight` | `/v1/insights/:id` | Yes |
| List | `listAiInsights` | `/v1/insights` | Yes |

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API's body parameters. For relation fields, render a dropdown loaded from the related object's list API using the display label property.



## AI Agents

This service exposes **1** AI agent as dedicated API endpoints. Each agent is a backend-managed AI pipeline with its own model, system prompt, and optional tool access. The frontend interacts with agents through standard HTTP requests — either synchronous REST calls or streaming SSE connections.

### Agent Overview

| Agent | Modality | Mode | REST | SSE | Auth | Path |
|-------|----------|------|------|-----|------|------|
| `insightGenerator` | text | task | Yes | Yes | Yes | `/ai-insight/generate` |

### Agent: `insightGenerator`

AI agent for generating company workforce insights. Accesses all company data (employees, departments, attendance, tasks, leave) to provide contextual answers based on actual company data. For general workforce questions, provides general advice. For company-specific questions, analyzes the data and provides data-driven insights.

- **Modality:** `text` — text-in, text-out
- **Execution Mode:** `task` — single request/response (one-shot)
- **Provider / Model:** `openai` / `gpt-4o`
- **Response Format:** `json`
- **Token Budget:** 5000
- **Timeout:** 120000ms

#### REST Endpoint (Synchronous)

```
POST {baseUrl}/ai-insight/generate
Authorization: Bearer {accessToken}
Content-Type: application/json
```

**Request Body:**

```json
{
  "prompt": "Your message or instruction to the agent"
}
```
**Response:**

```json
{
  "success": true,
  "data": {
    "response": "Agent response text"
  }
}
```

#### SSE Endpoint (Streaming)

```
POST {baseUrl}/ai-insight/generate/stream
Authorization: Bearer {accessToken}
Content-Type: application/json
```

The request body is the same as the REST endpoint. The response is a Server-Sent Events stream:

```
event: chunk
data: {"content":"partial response text..."}

event: chunk
data: {"content":"more text..."}

event: complete
data: {}
```

**Frontend integration pattern:**

```js
const response = await fetch(`${baseUrl}/ai-insight/generate/stream`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json',
    'mbx-company-codename': tenantCodename,
  },
  body: JSON.stringify({ prompt: userMessage }),
});

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });

  const lines = buffer.split('\n');
  buffer = lines.pop() || '';

  for (const line of lines) {
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.slice(6));
      if (data.content) {
        // Append data.content to UI (streaming text)
      }
    }
  }
}
```



## API Reference

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

**API Frontend Description By The Backend Architect**

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

**Rest Route**

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

`/v1/aiinsights`


**Rest Request Parameters**


The `createAiInsight` api has got 6 regular request parameters  

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



**REST Request**
To access the api you can use the **REST** controller with the path **POST  /v1/aiinsights**
```js
  axios({
    method: 'POST',
    url: '/v1/aiinsights',
    data: {
            insightType:"String",  
            audienceUserId:"ID",  
            applicablePeriod:"Object",  
            details:"Text",  
            aiStatus:"Enum",  
            deliveredTime:"Date",  
    
    },
    params: {
    
        }
  });
```   
**REST Response**


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


### `Update Aiinsight` API
**[Default update API]** — This is the designated default `update` API for the `aiInsight` data object. Frontend generators and AI agents should use this API for standard CRUD operations.
Internal/system API for updating an existing AI insight (e.g., set as delivered, correction, or error annotation). Requires AI subscription. Used by scheduled delivery jobs, agent code, or admin.

**API Frontend Description By The Backend Architect**

Used internally to update AI insight status, e.g. after delivery or error. Not end-user facing.

**Rest Route**

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

`/v1/aiinsights/:aiInsightId`


**Rest Request Parameters**


The `updateAiInsight` api has got 7 regular request parameters  

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



**REST Request**
To access the api you can use the **REST** controller with the path **  /v1/aiinsights/:aiInsightId**
```js
  axios({
    method: '',
    url: `/v1/aiinsights/${aiInsightId}`,
    data: {
            insightType:"String",  
            audienceUserId:"ID",  
            applicablePeriod:"Object",  
            details:"Text",  
            aiStatus:"Enum",  
            deliveredTime:"Date",  
    
    },
    params: {
    
        }
  });
```   
**REST Response**


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


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

**API Frontend Description By The Backend Architect**

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

**Rest Route**

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

`/v1/insights/:id`


**Rest Request Parameters**


The `getAiInsight` api has got 2 regular request parameters  

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



**REST Request**
To access the api you can use the **REST** controller with the path **GET  /v1/insights/:id**
```js
  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.

```json
{
	"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**
```js
  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.

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


### `Delete Aiinsight` API
Delete (soft) an AI insight. Only allowed for superAdmin/saasAdmin or tenantOwner/admin for own tenant, in error/cancel scenarios. Not a standard operational API.

**API Frontend Description By The Backend Architect**

Not end user facing—admin tool for error/corrections only.

**Rest Route**

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

`/v1/aiinsights/:aiInsightId`


**Rest Request Parameters**


The `deleteAiInsight` api has got 1 regular request parameter  

| Parameter              | Type                   | Required | Population                   |
| ---------------------- | ---------------------- | -------- | ---------------------------- |
| aiInsightId  | ID  | true | request.params?.["aiInsightId"] |
**aiInsightId** : This id paremeter is used to select the required data object that will be deleted



**REST Request**
To access the api you can use the **REST** controller with the path **  /v1/aiinsights/:aiInsightId**
```js
  axios({
    method: '',
    url: `/v1/aiinsights/${aiInsightId}`,
    data: {
    
    },
    params: {
    
        }
  });
```   
**REST Response**


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


### `Save Insight` API
Saves an AI workforce insight from stream conversation to database for history tracking


**Rest Route**

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

`/v1/saveinsight`


**Rest Request Parameters**


The `saveInsight` api has got 13 regular request parameters  

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



**REST Request**
To access the api you can use the **REST** controller with the path **POST  /v1/saveinsight**
```js
  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**


```json
{
	"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**
```js
  axios({
    method: 'POST',
    url: '/v1/save-insight',
    data: {
            insightType:"String",  
    
    },
    params: {
    
        }
  });
```   
**REST Response**


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



**After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.**


