Service Design Specification
workforceos-schedulemanagement-service documentation
Version: 1.0.11
Scope
This document provides a structured architectural overview of the scheduleManagement microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.
The document is intended to serve multiple audiences:
- Service architects can use it to validate design decisions and ensure alignment with broader architectural goals.
- Developers and maintainers will find it useful for understanding the structure and behavior of the service, facilitating easier debugging, feature extension, and integration with other systems.
- Stakeholders and reviewers can use it to gain a clear understanding of the service’s capabilities and domain logic.
Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.
Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.
ScheduleManagement Service Settings
Microservice managing shift scheduling, shift templates, assignment of users/departments to shifts, and schedule conflict detection for WorkforceOS.
Service Overview
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:
/healthand/admin/health - Current Session Info:
/currentuser - Favicon:
/favicon.ico
The service uses a PostgreSQL database for data storage, with the database name set to workforceos-schedulemanagement-service.
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
Authentication & Security
- Login Required: Yes
This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.
Service Data Objects
The service uses a PostgreSQL database for data storage, with the database name set to workforceos-schedulemanagement-service.
Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.
| Object Name | Description | Public Access | Tenant Level |
|---|---|---|---|
shiftTemplate |
Template for recurring or standard shift patterns. Owned by company. Used to quickly schedule repeatable work shifts; optionally scoped to a department. | accessPrivate | Yes |
shift |
A scheduled shift for a company. Defines date, time span, location, and assignment to users/departments. Core entity for workforce operations. | accessPrivate | Yes |
shiftTemplate Data Object
Object Overview
Description: Template for recurring or standard shift patterns. Owned by company. Used to quickly schedule repeatable work shifts; optionally scoped to a department.
This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement.
It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.
Core Configuration
- Soft Delete: Enabled — Determines whether records are marked inactive (
isActive = false) instead of being physically deleted. - Public Access: accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.
- Tenant-Level Scope: Yes — Enables data isolation per tenant by attaching a tenant ID field.
Properties Schema
Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.
| Property | Type | Required | Description |
|---|---|---|---|
name |
String | Yes | Display name for the template (e.g., 'Morning Shift'). |
description |
Text | No | Description/purpose of the shift template. |
startTime |
String | Yes | Template start time in HH:mm format. |
endTime |
String | Yes | Template end time in HH:mm format. |
recurrenceRule |
String | Yes | RFC 5545 RRULE-formatted string describing recurrence (e.g., weekly, biweekly). |
departmentId |
ID | No | Restricts applicability of template to a department if set. |
companyId |
ID | Yes | 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 is set.
- Properties marked
Type[] (array)MUST be sent as a JSON array (e.g.["a","b"]), even when only one value is present (["a"]). Sending a bare scalar fails validation.
Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.
- name: ‘default’
- startTime: ‘default’
- endTime: ‘default’
- recurrenceRule: ‘default’
- companyId: 00000000-0000-0000-0000-000000000000
Constant Properties
companyId
Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle.
A property is set to be constant if the Allow Update option is set to false.
Auto Update Properties
name description startTime endTime recurrenceRule departmentId
An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body.
If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false.
These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.
Elastic Search Indexing
name startTime endTime departmentId companyId
Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.
Database Indexing
name startTime endTime departmentId companyId
Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.
Secondary Key Properties
companyId
Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.
Relation Properties
departmentId
Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.
- departmentId: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
On Delete: Set Null Required: No
Filter Properties
name departmentId companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
-
name: String has a filter named
name -
departmentId: ID has a filter named
departmentId -
companyId: ID has a filter named
companyId
shift Data Object
Object Overview
Description: A scheduled shift for a company. Defines date, time span, location, and assignment to users/departments. Core entity for workforce operations.
This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement.
It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.
Core Configuration
- Soft Delete: Enabled — Determines whether records are marked inactive (
isActive = false) instead of being physically deleted. - Public Access: accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.
- Tenant-Level Scope: Yes — Enables data isolation per tenant by attaching a tenant ID field.
Properties Schema
| Property | Type | Required | Description |
|---|---|---|---|
shiftDate |
Date | Yes | Date of shift (YYYY-MM-DD). |
startTime |
String | Yes | Shift start time (HH:mm local time). |
endTime |
String | Yes | Shift end time (HH:mm local time). |
location |
String | No | Physical or logical location for the shift (if applicable). |
departmentId |
ID | No | Limits or indicates department responsible for this shift. |
assignedUserIds |
ID[] (array) | No | User IDs assigned to the shift. |
assignedDepartmentIds |
ID[] (array) | No | Department IDs (userGroups) assigned to the shift; employees in these groups are considered assigned. |
status |
Enum | Yes | Status of the shift (scheduled, completed, cancelled). |
createdBy |
ID | Yes | User who created the shift. |
companyId |
ID | Yes | 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 is set.
- Properties marked
Type[] (array)MUST be sent as a JSON array (e.g.["a","b"]), even when only one value is present (["a"]). Sending a bare scalar fails validation.
Array Properties
assignedUserIds assignedDepartmentIds
Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly.
Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.
Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.
- shiftDate: new Date()
- startTime: ‘default’
- endTime: ‘default’
- status: scheduled
- createdBy: ‘00000000-0000-0000-0000-000000000000’
- companyId: 00000000-0000-0000-0000-000000000000
Constant Properties
createdBy companyId
Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle.
A property is set to be constant if the Allow Update option is set to false.
Auto Update Properties
shiftDate startTime endTime location departmentId assignedUserIds assignedDepartmentIds status createdBy
An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body.
If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false.
These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.
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 addtional 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 index property to sort by the enum value or when your enum options represent a sequence of values.
- status: [scheduled, completed, cancelled]
Elastic Search Indexing
shiftDate startTime endTime location departmentId assignedUserIds assignedDepartmentIds status companyId
Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.
Database Indexing
shiftDate startTime endTime departmentId status companyId
Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.
Secondary Key Properties
companyId
Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.
Relation Properties
departmentId createdBy
Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.
- departmentId: ID
Relation to
userGroup.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
On Delete: Set Null Required: No
- createdBy: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
On Delete: Set Null Required: No
Session-sourced Properties
createdBy
These properties have source: 'session' — their values are read from the authenticated session at create/update time and cannot be supplied in the request body.
- createdBy: ID property will be mapped to the session parameter
userId.
This property is the data object’s ownership field, used by ownership-based access control.
Filter Properties
shiftDate departmentId assignedUserIds assignedDepartmentIds status companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
-
shiftDate: Date has a filter named
shiftDate -
departmentId: ID has a filter named
departmentId -
assignedUserIds: ID has a filter named
assignedUserIds -
assignedDepartmentIds: ID has a filter named
assignedDepartmentIds -
status: Enum has a filter named
status -
companyId: ID has a filter named
companyId
Business Logic
scheduleManagement has got 10 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.
Service Library
Functions
detectShiftAssignmentConflicts.js
/*
* Checks if any of the assigned users for the requested shift:
* 1. Are already assigned to another overlapping shift on the same date/time.
* 2. Have an approved leave request that covers the shift date.
* If isUpdate is true, ignores conflict with self (when updating an existing shift).
* Returns: Array of conflict objects with type, id, reason, and details.
*/
const { getShiftListByQuery } = require('dbLayer');
const { convertUserQueryToSequelizeQuery } = require('common/queryBuilder');
const { fetchRemoteListByMQuery } = require('serviceCommon');
function timeOverlap(startA, endA, startB, endB) {
return (startA < endB && endA > startB);
}
module.exports = async function detectShiftAssignmentConflicts(context, isUpdate) {
const { shiftDate, startTime, endTime, assignedUserIds = [], assignedDepartmentIds = [], id } = context;
if (!shiftDate || (!Array.isArray(assignedUserIds) && !Array.isArray(assignedDepartmentIds))) return [];
const conflicts = [];
// --- 1. Check overlapping shift assignments ---
const orConditions = [];
if (assignedUserIds.length) {
orConditions.push({ assignedUserIds: { $overlap: assignedUserIds } });
}
if (assignedDepartmentIds.length) {
orConditions.push({ assignedDepartmentIds: { $overlap: assignedDepartmentIds } });
}
if (orConditions.length > 0) {
const mscriptQuery = {
shiftDate,
status: { $ne: 'cancelled' },
$or: orConditions,
...(isUpdate && id ? { id: { $ne: id } } : {})
};
const sequelizeQuery = convertUserQueryToSequelizeQuery(mscriptQuery);
const candidateShifts = await getShiftListByQuery(sequelizeQuery);
for (const s of candidateShifts) {
if (timeOverlap(startTime, endTime, s.startTime, s.endTime)) {
for (const uid of assignedUserIds || []) {
if ((s.assignedUserIds || []).includes(uid)) {
conflicts.push({ type: 'user', id: uid, reason: 'shiftOverlap', conflictShiftId: s.id, conflictShiftStartTime: s.startTime, conflictShiftEndTime: s.endTime });
}
}
for (const did of assignedDepartmentIds || []) {
if ((s.assignedDepartmentIds || []).includes(did)) {
conflicts.push({ type: 'department', id: did, reason: 'shiftOverlap', conflictShiftId: s.id, conflictShiftStartTime: s.startTime, conflictShiftEndTime: s.endTime });
}
}
}
}
}
// --- 2. Check approved leave requests for assigned users ---
if (assignedUserIds.length > 0 && shiftDate) {
try {
// Normalize shiftDate to a comparable date string (YYYY-MM-DD)
const shiftDateObj = new Date(shiftDate);
const shiftDateStr = shiftDateObj.toISOString().split('T')[0];
// Query leaveRequest objects from the leaveManagement service via Elasticsearch.
// We look for approved leaves where startDate <= shiftDate AND endDate >= shiftDate
// for any of the assigned users.
const leaveQuery = {
status: 'approved',
userId: { $in: assignedUserIds },
startDate: { $lte: shiftDateStr + 'T23:59:59.999Z' },
endDate: { $gte: shiftDateStr + 'T00:00:00.000Z' }
};
const approvedLeaves = await fetchRemoteListByMQuery('leaveRequest', leaveQuery, 0, 500);
for (const leave of approvedLeaves) {
conflicts.push({
type: 'user',
id: leave.userId,
reason: 'approvedLeave',
leaveRequestId: leave.id,
leaveType: leave.leaveType,
leaveStartDate: leave.startDate,
leaveEndDate: leave.endDate
});
}
} catch (err) {
console.error('Error checking approved leaves for shift conflict detection:', err.message);
// Do not block shift creation if leave service is unavailable; log and continue.
}
}
return conflicts;
};
This document was generated from the service architecture definition and should be kept in sync with implementation changes.