metis-desk/modules/companies/src/api/domain/work-profile.aggregate.ts

86 lines
2.2 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";
2026-10-05 07:53:29 +00:00
import { Result } from "@repo/rdx-utils";
import { z } from "zod/v4";
2026-10-09 08:38:19 +00:00
import type { WorkProfileValues } from "./value-objects/work-profile-values.vo";
2026-10-05 07:53:29 +00:00
import { WorkProfileRevision } from "./work-profile-revision.entity";
import { WorkProfileError } from "./work-profile-values";
type WorkProfileProps = Readonly<{
companyId: UniqueID;
values: WorkProfileValues;
history: readonly WorkProfileRevision[];
}>;
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
export class WorkProfile extends AggregateRoot<WorkProfileProps> {
private constructor(props: WorkProfileProps, id?: UniqueID) {
super(Object.freeze({ ...props, history: Object.freeze([...props.history]) }), id);
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
static create(
companyId: UniqueID,
values: WorkProfileValues,
actorId: UniqueID,
recordedAt: string
): Result<WorkProfile, WorkProfileError> {
if (!z.iso.datetime().safeParse(recordedAt).success) {
return Result.fail(new WorkProfileError("INVALID_REQUEST"));
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
return Result.ok(
new WorkProfile({
companyId,
values,
history: [WorkProfileRevision.create({ values, actorId, recordedAt })],
})
);
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
static rehydrate(props: WorkProfileProps, id: UniqueID) {
return new WorkProfile(props, id);
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
get companyId() {
return this.props.companyId;
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
get values() {
return this.props.values;
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
get history() {
return this.props.history;
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
update(
values: WorkProfileValues,
actorId: UniqueID,
recordedAt: string
): Result<WorkProfile, WorkProfileError> {
if (this.values.equals(values)) {
return Result.ok(this);
}
if (!this.values.sameTarget(values)) {
return Result.fail(new WorkProfileError("PROFILE_TARGET_IMMUTABLE"));
}
if (
!z.iso.datetime().safeParse(recordedAt).success ||
recordedAt < (this.history.at(-1)?.recordedAt ?? "")
) {
return Result.fail(new WorkProfileError("INVALID_REQUEST"));
}
2026-10-10 10:01:58 +00:00
2026-10-05 07:53:29 +00:00
return Result.ok(
new WorkProfile(
{
...this.props,
values,
history: [...this.history, WorkProfileRevision.create({ values, actorId, recordedAt })],
},
this.id
)
);
}
}