import type { UniqueID } from "@repo/rdx-ddd"; import { Result } from "@repo/rdx-utils"; import type { Asset } from "../domain/asset.aggregate"; import type { AssetCatalog } from "../domain/asset-catalog.aggregate"; import { AssetCatalogError } from "../domain/asset-definition"; import type { AssetRelationship } from "../domain/asset-relationship.aggregate"; import type { AssetValues } from "../domain/value-objects/asset-values"; import type { Workstation } from "../domain/workstation.aggregate"; export type InventoryContext = Readonly<{ workstations: readonly Workstation[]; catalog: AssetCatalog; assets: readonly Asset[]; relationships: readonly AssetRelationship[]; sites: readonly UniqueID[]; people: readonly { id: UniqueID; active: boolean }[]; actorNames: ReadonlyMap; }>; export interface IAssetRepository { saveWorkstation( companyId: UniqueID, action: (context: InventoryContext) => Result ): Promise< Result<{ workstation: Workstation; actorNames: ReadonlyMap }, AssetCatalogError> >; get(companyId: UniqueID): Promise>; saveRelationship( companyId: UniqueID, action: (context: InventoryContext) => Result ): Promise< Result< { relationship: AssetRelationship; actorNames: ReadonlyMap }, AssetCatalogError > >; save( companyId: UniqueID, action: (context: InventoryContext) => Result ): Promise }, AssetCatalogError>>; } export function validateAssetReferences( context: InventoryContext, values: AssetValues, previous?: Asset ) { const next = values.toPrimitive(); const current = previous?.values.toPrimitive(); if (next.siteId && !context.sites.some((site) => site.toPrimitive() === next.siteId)) { return Result.fail(new AssetCatalogError("SITE_NOT_FOUND")); } if (next.personId) { const person = context.people.find((person) => person.id.toPrimitive() === next.personId); if (!person || (!person.active && current?.personId !== next.personId)) { return Result.fail(new AssetCatalogError("PERSON_UNAVAILABLE")); } } return Result.ok(true); }