@upv/ushi-shared
Version:
Shared DTOs, types, and utilities for the USHI platform (LMS, Trials, Social, Wallet).
75 lines (74 loc) • 2.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAdmin = isAdmin;
exports.isTrialRole = isTrialRole;
exports.getActiveAssignmentsForPerson = getActiveAssignmentsForPerson;
exports.isRoleStillValid = isRoleStillValid;
exports.validateRoleAssignments = validateRoleAssignments;
// utils/roles.ts
const PersonEnums_1 = require("../core/enums/PersonEnums");
function isAdmin(role) {
return role === PersonEnums_1.PersonRole.ADMIN;
}
function isTrialRole(role) {
return [
PersonEnums_1.PersonRole.PARTICIPANT,
PersonEnums_1.PersonRole.RESEARCHER,
PersonEnums_1.PersonRole.ORGANIZER,
PersonEnums_1.PersonRole.SPONSOR,
].includes(role);
}
/**
* getActiveAssignmentsForPerson
*
* Filters role assignments to include only those that:
* - belong to the specified user
* - are currently active
* - have not expired
*
* @param userId - The user ID to filter by
* @param assignments - All role assignments in the system
* @param now - Optional override for current time (defaults to Date.now())
* @returns Array of active, non-expired role assignments
*/
function getActiveAssignmentsForPerson(userId, assignments, now = Date.now()) {
return assignments.filter((a) => a.userId === userId &&
a.status === 'active' &&
(!a.expiresAt || a.expiresAt > now));
}
/**
* isRoleStillValid
*
* Determines whether a single role assignment is still valid
* (i.e., active and not expired).
*
* @param assignment - The assignment to check
* @param now - Optional override for current time (defaults to Date.now())
* @returns True if the role is valid, otherwise false
*/
function isRoleStillValid(assignment, now = Date.now()) {
return (assignment.status === 'active' &&
(!assignment.expiresAt || assignment.expiresAt > now));
}
/**
* validateRoleAssignments
*
* Returns a new list of role assignments with any expired roles
* marked as `status: 'expired'`.
*
* NOTE: This function is non-mutative.
*
* @param assignments - List of role assignments to validate
* @param now - Optional override for current time (defaults to Date.now())
* @returns Updated list of role assignments
*/
function validateRoleAssignments(assignments, now = Date.now()) {
return assignments.map((assignment) => {
const hasExpired = assignment.status === 'active' &&
assignment.expiresAt !== null &&
assignment.expiresAt <= now;
return hasExpired
? { ...assignment, status: 'expired' }
: assignment;
});
}