import { Result } from "@repo/rdx-utils"; import type { TeleworkAuthorization } from "../domain/telework-authorization.aggregate"; import type { TeleworkAuthorizationInput } from "../domain/telework-authorization-values"; import { TeleworkAuthorizationError } from "../domain/telework-authorization-values"; import { TeleworkAuthorizationValues } from "../domain/value-objects/telework-authorization-values.vo"; import type { TeleworkAuthorizationContext } from "./telework-authorization.repository"; export function mapTeleworkAuthorizationInput( input: TeleworkAuthorizationInput, context: TeleworkAuthorizationContext, previous?: TeleworkAuthorization ) { const mapped = TeleworkAuthorizationValues.create(input); if (!mapped.isSuccess) { return mapped; } const values = mapped.data; if (previous && !previous.values.sameTarget(values)) { return Result.fail(new TeleworkAuthorizationError("TELEWORK_PERSON_IMMUTABLE")); } const person = context.people.find((item) => item.id.equals(values.personId)); if (!person) { return Result.fail(new TeleworkAuthorizationError("TELEWORK_PERSON_NOT_FOUND")); } // Se permite revocar y anotar una autorización de una persona inactiva, sin ocultar sus accesos pendientes. if ( values.active && !person.active && !(previous?.values.active && previous.values.equals(values)) ) { return Result.fail(new TeleworkAuthorizationError("TELEWORK_PERSON_INACTIVE")); } if ( context.authorizations.some( (item) => item.id.toPrimitive() !== previous?.id.toPrimitive() && item.values.sameTarget(values) ) ) { return Result.fail(new TeleworkAuthorizationError("TELEWORK_ALREADY_EXISTS")); } return mapped; }