Personnel Management API
The Personnel API provides comprehensive endpoints for managing staff members, including registration, profile updates, role assignments, operational assignments, and access control. This module enforces labor status validation, tracks absence history, and maintains full audit trails for all personnel changes.Permissions
All personnel endpoints require authentication and specific permissions:- VIEW_STAFF - Required for viewing personnel data
- MANAGE_STAFF - Required for creating, updating, and managing staff
- ASSIGN_OPERATIONS - Required for assigning personnel to operational tasks
Get All Staff
Authorization
Required Permission:VIEW_STAFF
Response Schema
Returns an enriched list of all personnel with computed state information:Indicates if the request was successful
Array of personnel objects
Unique personnel identifier
First name
Last name
Internal employee code (also used as username)
Foreign key to areas table
Area name (e.g., “Producción”, “Administración”)
Email address
Phone number
Date of hire (YYYY-MM-DD format)
Organizational role title
Current labor status. One of:
Activo, Incapacitado, Inactivo, BajaCurrent system role name
Login username (same as codigo_interno)
User account status:
Activo or InactivoComputed effective status. Automatically reverts to
Activo if absence period has expiredIndicates if the absence period has expired and auto-reactivation occurred
Whether this person is an active auxiliary (Auxiliar operational role + Activo state)
Start date of current absence (YYYY-MM-DD)
End date of current absence (YYYY-MM-DD)
Type of absence:
Incapacidad or PermisoReason for absence
Business Logic
- Auto-Reactivation: Staff with expired absence periods (
ausencia_hasta< today) are automatically transitioned back toActivostatus - State Enrichment: The response includes both
estado_laboral(stored) andestado_efectivo(computed) - Audit Trail: Auto-reactivations are logged with reason
"Retorno automático por vencimiento de ausencia"
Get Staff Details
Parameters
Personnel ID
Authorization
Required Permission:VIEW_STAFF
Response Schema
Returns comprehensive personnel details including all related history:Request success indicator
Detailed personnel information
Complete history of system role assignments
Active operational assignments (process + machine assignments)
Current operational role (e.g., “Operador Especializado”, “Auxiliar”)
History of group memberships
Complete absence history with reasons and dates
Register Staff
Authorization
Required Permission:MANAGE_STAFF
Request Body
First name (minimum 1 character)
Last name (minimum 1 character)
Unique internal employee code. Will be used as the username. Must not already exist in the system.
Area ID (must be a valid area from the areas catalog)
Email address. Must be unique if provided.
Phone number
Date of hire in YYYY-MM-DD format
Organizational role title (minimum 1 character)
Response Schema
Request success indicator
Success message
Business Logic
- Uniqueness Validation: The system validates that both
codigo_internoandemailare unique - Automatic User Account: A user account is automatically created with:
- Username =
codigo_interno - Auto-generated temporary password (8 characters)
- Default role: “Operario” (or first available role)
must_change_passwordflag set totrue
- Username =
- Transaction Safety: The entire operation runs within a database transaction
- Audit Trail: Creation is logged with reason “Registro inicial de personal y usuario”
- Password Security: Passwords are hashed using bcrypt with 10 rounds
Error Responses
Update Staff
Parameters
Personnel ID to update
Authorization
Required Permission:MANAGE_STAFF
Request Body (All fields optional)
First name
Last name
Email address
Phone number
Area ID
Organizational role title
Labor status. One of:
Activo, Incapacitado, Inactivo, BajaStart date of absence (YYYY-MM-DD). Required when estado_laboral is
Incapacitado, Inactivo, or BajaEnd date of absence (YYYY-MM-DD). Required for
Incapacitado and Inactivo. Must be null for BajaType of absence:
Incapacidad or Permiso. Must match estado_laboral constraintsReason for absence (minimum 5 characters). Required for all non-Activo states
Reason for the update (minimum 5 characters). Required for audit trail
Category of the change reason for audit classification
Business Logic
Terminal State Protection
- Staff with
estado_laboral = "Baja"cannot be modified. Returns error: “Estado terminal: No se pueden realizar cambios en un colaborador dado de Baja”
Estado Laboral Rules
Incapacitado:- Requires:
ausencia_desde,ausencia_hasta,tipo_ausencia = "Incapacidad",motivo_ausencia - System validates that tipo_ausencia is “Incapacidad”
- Requires:
ausencia_desde,ausencia_hasta,tipo_ausencia = "Permiso",motivo_ausencia - System validates that tipo_ausencia is “Permiso”
- Requires:
ausencia_desde,motivo_ausencia - System automatically sets:
ausencia_hasta = null,tipo_ausencia = null - This is a terminal state - no further modifications allowed
- System automatically clears all absence fields:
ausencia_desde,ausencia_hasta,tipo_ausencia,motivo_ausencia= null
Audit Trail
- All changes are logged to the audit system
- State changes trigger
logStatusChange - Other updates trigger
logUpdatewith before/after comparison - Absence history is saved to
historial_ausenciastable for non-Activo transitions
Error Responses
Assign Role
Parameters
Personnel ID
Authorization
Required Permission:MANAGE_STAFF
Request Body
System role ID to assign. Must be a valid role from the roles catalog.
Reason for the role change (minimum 5 characters). Required for audit trail.
Mark this change as a correction. If true, “[CORRECCIÓN]” prefix is added to motivo_cambio.
Category of the change reason for audit classification
Business Logic
- Terminal State Protection: Cannot assign roles to staff with
estado_laboral = "Baja" - Transaction Safety: Role assignment runs within a database transaction
- Historical Tracking:
- Previous role assignment is deactivated (
activo = 0) - New role assignment is inserted into
persona_rolestable withactivo = 1 - Current role in
usuariostable is updated
- Previous role assignment is deactivated (
- Audit Trail: Comprehensive audit log created with action
ROLE_CHANGE - Correction Support: If
es_correccion = true, the motivo is prefixed with “[CORRECCIÓN]“
Error Responses
Reset Password
Parameters
Personnel ID
Authorization
Required Permission:MANAGE_STAFF
Response Schema
Request success indicator
Business Logic
- Password Generation: System generates a random 8-character alphanumeric password
- Password Hashing: Password is hashed with bcrypt (10 rounds) before storage
- Force Change: The
must_change_passwordflag is automatically set totrue - Audit Trail: Logged with action
PASSWORD_RESETand reason “Reset de contraseña por administrador” - User Validation: Verifies that the person has an associated user account
Assign Operation
Parameters
Personnel ID to assign
Authorization
Required Permission:ASSIGN_OPERATIONS
Request Body
Process ID to assign the person to. Must be a valid process from ProcessRegistry.
Machine ID if the assignment is machine-specific. Machine must exist and not be in “Baja” or “Fuera de servicio” status.
Shift identifier (e.g., “T1”, “T2”, “T3”, “T4”)
Whether this is a permanent assignment
Reason for the assignment (minimum 5 characters). Defaults to “Asignación operativa regular”
Mark this assignment as a correction. If true, “[CORRECCIÓN]” prefix is added.
Category of the assignment for audit classification
Business Logic
Assignment Validation
-
Personnel State Validation:
- Only staff with
estado_laboral = "Activo"can be assigned - Returns error: “Asignación bloqueada: El colaborador se encuentra en estado . Solo colaboradores en estado Activo pueden participar en la operación.”
- Only staff with
-
User Account Validation:
- Personnel must have an associated user account
- Technical admin user cannot be assigned to operations
-
Machine Validation (if maquina_id provided):
- Machine must exist
- Machine cannot be in “Baja” or “Fuera de servicio” status
- Returns error: “Asignación bloqueada: La máquina se encuentra en estado .”
- Transaction Safety: All validations and inserts run within a database transaction
-
Audit Trail: Logged with action
OPERATIONAL_ASSIGNMENTincluding proceso_id, maquina_id, and turno
Error Responses
Toggle Access
Parameters
Personnel ID
Authorization
Required Permission:MANAGE_STAFF
Request Body
Whether to activate or deactivate system access
Business Logic
- Area Restriction: This endpoint only works for personnel in the “Producción” area
- Terminal State Protection: Cannot toggle access for staff with
estado_laboral = "Baja" - User Validation: Verifies that the person has an associated user account
- State Update: Updates
estado_usuarioin theusuariostable to “Activo” or “Inactivo” - Audit Trail: Logged with action
TOGGLE_ACCESOshowing before/after estado_usuario values
This feature is specifically designed for production floor personnel who may need temporary access suspension without changing their labor status.
Error Responses
Get Catalogs
Authorization
Required Permission:VIEW_STAFF
Response Schema
Returns reference catalogs used for personnel management:Request success indicator
Usage
This endpoint provides the catalog data needed for:- Populating dropdown menus in personnel forms
- Validating area_id and rol_id in other endpoints
- Displaying human-readable area and role names
Get Operational Roles
Authorization
Required Permission:VIEW_STAFF
Response Schema
Returns the list of operational roles (distinct from system roles):Request success indicator
Operational Roles vs System Roles
System Roles control permissions and access levels in the application (e.g., Administrador, Supervisor, Operario).Operational Roles define production floor responsibilities and competencies (e.g., Auxiliar, Operador Especializado, Técnico).A person can have one system role and one operational role simultaneously.
Data Models
Personnel Entity
Core personnel record stored in thepersonas table:
User Account Entity
Authentication and authorization data stored in theusuarios table:
Operational Assignment Entity
Stored inasignaciones_operativas table:
Best Practices
State Management
-
Always check estado_efectivo: When displaying personnel status, use
estado_efectivorather thanestado_laboralto account for expired absences -
Respect terminal states: The
Bajastatus is terminal and immutable. Design your UI to prevent modification attempts - Validate absence data: When changing to non-Activo states, ensure all required absence fields are provided
Security
- Permission enforcement: All endpoints enforce role-based access control. Ensure your client application handles 403 Forbidden responses
- Password handling: Never log or store temporary passwords. Send them via secure channels only
-
Audit trail compliance: Always provide meaningful
motivo_cambiovalues for audit compliance
Performance
- Use GET /catalogos once: Cache the areas and roles catalogs in your client application rather than fetching on every form render
- Batch operations: When updating multiple personnel records, make parallel requests to improve throughput
- Detail endpoint for full data: Use GET /:id only when you need complete historical data. Use GET / for listing views