Service Design Specification
workforceos-payrollreporting-service documentation
Version: 1.0.9
Scope
This document provides a structured architectural overview of the payrollReporting 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.
PayrollReporting Service Settings
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.
Service Overview
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:
/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-payrollreporting-service.
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
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-payrollreporting-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 |
|---|---|---|---|
payrollReport |
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). | accessProtected | Yes |
payrollReport Data Object
Object Overview
Description: 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).
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: accessProtected — 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.
Composite Indexes
- user_period_unique: [userId, periodStart, periodEnd] This composite index is defined to optimize query performance for complex queries involving multiple fields.
The index also defines a conflict resolution strategy for duplicate key violations.
When a new record would violate this composite index, the following action will be taken:
On Duplicate: doUpdate
The existing record will be updated with the new data.No error will be thrown.
Properties Schema
| Property | Type | Required | Description |
|---|---|---|---|
userId |
ID | Yes | Reference to the user/employee this report summarizes (auth:user.id). |
periodStart |
Date | Yes | Start date of reporting/payroll period (inclusive). |
periodEnd |
Date | Yes | End date of the reporting/payroll period (inclusive). |
totalHoursWorked |
Double | Yes | Total hours worked during this period (summed from attendance data, auto-calculated). |
overtimeHours |
Double | Yes | Total overtime hours for period (auto-calculated from attendance, company policy). |
absenceDays |
Integer | Yes | Total days absent during period (from leave & attendance). Auto-calculated. |
bonus |
Double | No | Manual bonus to add for this period (optional entry by admin/manager only). |
deduction |
Double | No | Manual deduction for this period (optional entry by admin/manager only). |
salaryCalculated |
Double | Yes | Auto-calculated salary for the period: base salary, hours, overtime, bonuses, and deductions. Always calculated, never direct entry. |
paymentStatus |
Enum | Yes | Manual entry tracking payment status for this period ('paid', 'unpaid', 'partial', 'pending'). |
paymentDate |
Date | No | Manual entry of actual date payment was made for this period (optional, admins/managers only). |
notes |
String | No | Optional notes (manual, internal)—remark/history on payment changes, bonuses, or irregularities. |
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.
- userId: ‘00000000-0000-0000-0000-000000000000’
- periodStart: new Date()
- periodEnd: new Date()
- paymentStatus: pending
- companyId: 00000000-0000-0000-0000-000000000000
Constant Properties
userId periodStart periodEnd totalHoursWorked overtimeHours absenceDays salaryCalculated 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
bonus deduction paymentStatus paymentDate notes
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.
- paymentStatus: [paid, unpaid, partial, pending]
Elastic Search Indexing
userId periodStart periodEnd totalHoursWorked overtimeHours absenceDays bonus deduction salaryCalculated paymentStatus paymentDate notes 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
userId periodStart periodEnd 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
userId
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.
- userId: ID
Relation to
user.id
The target object is a sibling object, meaning that the relation is a many-to-one or one-to-one relationship from this object to the target.
On Delete: Set Null Required: Yes
CustomData-sourced Properties
totalHoursWorked overtimeHours absenceDays salaryCalculated
These properties have source: 'customData' — every create/update API on this data object declares the value via apiOptions.dataClauseSettings.customData[]. Refer to the per-API documentation for the concrete value each API writes.
Filter Properties
userId periodStart periodEnd paymentStatus companyId
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
-
userId: ID has a filter named
userId -
periodStart: Date has a filter named
periodStart -
periodEnd: Date has a filter named
periodEnd -
paymentStatus: Enum has a filter named
paymentStatus -
companyId: ID has a filter named
companyId
Business Logic
payrollReporting has got 4 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.
Service Library
Functions
calculateTotalHoursWorked.js
// Computes total worked hours for given user within [periodStart, periodEnd].
// Attendance records with status 'present' or 'late' are counted as working hours.
// Args: context (Business API ctx), userId, periodStart, periodEnd
const { fetchRemoteListByMQuery } = require('serviceCommon');
module.exports = async function calculateTotalHoursWorked(context, userId, periodStart, periodEnd) {
if (!userId || !periodStart || !periodEnd) return 0;
const records = await fetchRemoteListByMQuery(
'attendanceRecord',
{
userId: userId,
checkInTime: { $gte: periodStart },
checkOutTime: { $lte: periodEnd },
status: { $in: ['present', 'late', 'leftEarly'] },
isActive: true
},
0,
3000 // practical max per period
);
let total = 0;
for (const rec of records) {
if (rec.checkInTime && rec.checkOutTime) {
const hours = (new Date(rec.checkOutTime) - new Date(rec.checkInTime)) / (60 * 60 * 1000);
total += Math.max(hours, 0.0);
}
}
return Number(total.toFixed(2));
};
calculateOvertimeHours.js
// Computes total overtime hours in attendance within [periodStart, periodEnd].
// Overtime: working over 8 hours/shift (could be customized)
const { fetchRemoteListByMQuery } = require('serviceCommon');
module.exports = async function calculateOvertimeHours(context, userId, periodStart, periodEnd) {
if (!userId || !periodStart || !periodEnd) return 0;
const records = await fetchRemoteListByMQuery(
'attendanceRecord',
{
userId: userId,
checkInTime: { $gte: periodStart },
checkOutTime: { $lte: periodEnd },
status: { $in: ['present', 'late', 'leftEarly'] },
isActive: true
},
0,
3000
);
let overtime = 0;
for (const rec of records) {
if (rec.checkInTime && rec.checkOutTime) {
const hours = (new Date(rec.checkOutTime) - new Date(rec.checkInTime)) / (60 * 60 * 1000);
if (hours > 8) overtime += (hours - 8);
}
}
return Number(overtime.toFixed(2));
};
calculateAbsenceDays.js
// Absence = days with leaveRequest.status === 'approved' or
// attendance status === 'absent' during period
const { fetchRemoteListByMQuery } = require('serviceCommon');
module.exports = async function calculateAbsenceDays(context, userId, periodStart, periodEnd) {
if (!userId || !periodStart || !periodEnd) return 0;
// Attendance absences
const attendance = await fetchRemoteListByMQuery(
'attendanceRecord',
{
userId: userId,
checkInTime: { $gte: periodStart },
checkOutTime: { $lte: periodEnd },
status: 'absent',
isActive: true
}, 0, 3000
);
let absentDays = new Set();
for (const rec of attendance) {
if (rec.checkInTime) absentDays.add((new Date(rec.checkInTime)).toISOString().slice(0,10));
}
// Leave requests
const leaveRequests = await fetchRemoteListByMQuery(
'leaveRequest',
{
userId: userId,
status: 'approved',
startDate: { $lte: periodEnd },
endDate: { $gte: periodStart },
isActive: true
}, 0, 200
);
for (const leave of leaveRequests) {
let d1 = new Date(leave.startDate), d2 = new Date(leave.endDate);
for (let d = d1; d <= d2; d.setDate(d.getDate() + 1)) {
const day = new Date(d).toISOString().slice(0,10);
if ( (day >= periodStart && day <= periodEnd) ) absentDays.add(day)
}
}
return absentDays.size;
};
calculateSalary.js
// Salary calculated based on policy: hourlyRate from employeeProfile/position, multiply worked+overtime, add bonus, subtract deduction. No payments processed. Placeholder: baseRate = 15/hr, overtimeRate = 1.5x
const { fetchRemoteObjectByMQuery } = require('serviceCommon');
module.exports = async function calculateSalary(context, userId, periodStart, periodEnd, totalHoursWorked, overtimeHours, bonus, deduction) {
if (!userId || !periodStart || !periodEnd) return 0;
// Fetch employee profile to get salary/position if defined
let baseRate = 15, overtimeRate = 1.5 * baseRate;
const empProf = await fetchRemoteObjectByMQuery("employeeProfile", { userId });
if (empProf && empProf.salary && empProf.salary > 0) baseRate = empProf.salary / 160; // Assume salary is monthly, 160h month
let base = Number(totalHoursWorked || 0) * baseRate;
let ot = Number(overtimeHours || 0) * overtimeRate;
let gross = base + ot + Number(bonus||0) - Number(deduction||0);
return Number(gross.toFixed(2));
};
This document was generated from the service architecture definition and should be kept in sync with implementation changes.