51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
import { Result } from "@repo/rdx-utils";
|
|
|
|
import type { SupportConnection } from "../domain/support-connection.aggregate";
|
|
import type { SupportInput } from "../domain/support-values";
|
|
import { SupportError } from "../domain/support-values";
|
|
import { SupportValues } from "../domain/value-objects/support-values";
|
|
|
|
import type { SupportContext } from "./support.repository";
|
|
export function mapSupportInput(
|
|
input: SupportInput,
|
|
context: SupportContext,
|
|
previous?: SupportConnection
|
|
) {
|
|
const values = SupportValues.create(input);
|
|
if (!values.isSuccess) {
|
|
return values;
|
|
}
|
|
const tool = context.tools.find((item) => item.id.equals(values.data.toolId));
|
|
if (!(tool && (tool.active || previous?.values.toolId.equals(tool.id)))) {
|
|
return Result.fail(new SupportError("TOOL_UNAVAILABLE"));
|
|
}
|
|
if (context.assetRetired && input.state !== "retired") {
|
|
return Result.fail(new SupportError("ASSET_RETIRED"));
|
|
}
|
|
if (
|
|
input.preferred &&
|
|
context.connections.some(
|
|
(item) =>
|
|
item.values.toPrimitive().preferred && item.id.toPrimitive() !== previous?.id.toPrimitive()
|
|
)
|
|
) {
|
|
return Result.fail(new SupportError("PREFERRED_EXISTS"));
|
|
}
|
|
const next = values.data.toPrimitive();
|
|
if (
|
|
next.state !== "retired" &&
|
|
context.connections.some((item) => {
|
|
const other = item.values.toPrimitive();
|
|
return (
|
|
item.id.toPrimitive() !== previous?.id.toPrimitive() &&
|
|
other.state !== "retired" &&
|
|
other.toolId === next.toolId &&
|
|
other.destination.toLowerCase() === next.destination.toLowerCase()
|
|
);
|
|
})
|
|
) {
|
|
return Result.fail(new SupportError("CONNECTION_EXISTS"));
|
|
}
|
|
return values;
|
|
}
|