metis-desk/modules/companies/src/api/application/telework-authorization.use-cases.ts
2026-10-10 12:01:58 +02:00

57 lines
2.0 KiB
TypeScript

import { UniqueID } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { TeleworkAuthorization } from "../domain/telework-authorization.aggregate";
import type { TeleworkAuthorizationInput } from "../domain/telework-authorization-values";
import { TeleworkAuthorizationError } from "../domain/telework-authorization-values";
import type { ITeleworkAuthorizationRepository } from "./telework-authorization.repository";
import { mapTeleworkAuthorizationInput } from "./telework-authorization-input.mapper";
export class TeleworkAuthorizationUseCases {
constructor(private readonly repository: ITeleworkAuthorizationRepository) {}
get(companyId: string) {
const company = UniqueID.create(companyId);
return company.isSuccess
? this.repository.get(company.data)
: Promise.resolve(Result.fail(new TeleworkAuthorizationError("INVALID_REQUEST")));
}
save(
companyId: string,
id: string | undefined,
input: TeleworkAuthorizationInput,
actorId: string
) {
const company = UniqueID.create(companyId);
const actor = UniqueID.create(actorId);
const identity = id ? UniqueID.create(id) : undefined;
if (!(company.isSuccess && actor.isSuccess) || (identity && !identity.isSuccess)) {
return Promise.resolve(Result.fail(new TeleworkAuthorizationError("INVALID_REQUEST")));
}
return this.repository.save(company.data, (context) => {
const previous = identity?.isSuccess
? context.authorizations.find((item) => item.id.equals(identity.data))
: undefined;
if (id && !previous) {
return Result.fail(new TeleworkAuthorizationError("TELEWORK_AUTHORIZATION_NOT_FOUND"));
}
const values = mapTeleworkAuthorizationInput(input, context, previous);
if (!values.isSuccess) {
return Result.fail(values.error);
}
const now = new Date().toISOString();
return previous
? previous.update(values.data, actor.data, now)
: TeleworkAuthorization.create(company.data, values.data, actor.data, now);
});
}
}