metis-desk/modules/companies/src/api/domain/telework-authorization.aggregate.ts

89 lines
2.5 KiB
TypeScript
Raw Normal View History

2026-10-08 14:43:34 +00:00
import type { UniqueID } from "@repo/rdx-ddd";
import { AggregateRoot } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import { z } from "zod/v4";
import { TeleworkAuthorizationRevision } from "./telework-authorization-revision.entity";
import { TeleworkAuthorizationError } from "./telework-authorization-values";
2026-10-09 08:38:19 +00:00
import type { TeleworkAuthorizationValues } from "./value-objects/telework-authorization-values.vo";
type TeleworkAuthorizationProps = Readonly<{
companyId: UniqueID;
values: TeleworkAuthorizationValues;
history: readonly TeleworkAuthorizationRevision[];
}>;
2026-10-10 10:01:58 +00:00
export class TeleworkAuthorization extends AggregateRoot<TeleworkAuthorizationProps> {
private constructor(props: TeleworkAuthorizationProps, id?: UniqueID) {
super(Object.freeze({ ...props, history: Object.freeze([...props.history]) }), id);
}
2026-10-10 10:01:58 +00:00
static create(
companyId: UniqueID,
values: TeleworkAuthorizationValues,
actorId: UniqueID,
recordedAt: string
): Result<TeleworkAuthorization, TeleworkAuthorizationError> {
if (!z.iso.datetime().safeParse(recordedAt).success) {
return Result.fail(new TeleworkAuthorizationError("INVALID_REQUEST"));
}
2026-10-10 10:01:58 +00:00
return Result.ok(
new TeleworkAuthorization({
companyId,
values,
history: [TeleworkAuthorizationRevision.create({ values, actorId, recordedAt })],
})
);
}
2026-10-10 10:01:58 +00:00
static rehydrate(props: TeleworkAuthorizationProps, id: UniqueID) {
return new TeleworkAuthorization(props, id);
}
2026-10-10 10:01:58 +00:00
get companyId() {
return this.props.companyId;
}
2026-10-10 10:01:58 +00:00
get values() {
return this.props.values;
}
2026-10-10 10:01:58 +00:00
get history() {
return this.props.history;
}
2026-10-10 10:01:58 +00:00
update(
values: TeleworkAuthorizationValues,
actorId: UniqueID,
recordedAt: string
): Result<TeleworkAuthorization, TeleworkAuthorizationError> {
if (this.values.equals(values)) {
return Result.ok(this);
}
if (!this.values.sameTarget(values)) {
return Result.fail(new TeleworkAuthorizationError("TELEWORK_PERSON_IMMUTABLE"));
}
if (
!z.iso.datetime().safeParse(recordedAt).success ||
recordedAt < (this.history.at(-1)?.recordedAt ?? "")
) {
return Result.fail(new TeleworkAuthorizationError("INVALID_REQUEST"));
}
2026-10-10 10:01:58 +00:00
return Result.ok(
new TeleworkAuthorization(
{
...this.props,
values,
history: [
...this.history,
TeleworkAuthorizationRevision.create({ values, actorId, recordedAt }),
],
},
this.id
)
);
}
}