54 lines
2.0 KiB
TypeScript
54 lines
2.0 KiB
TypeScript
|
|
import { Result } from "@repo/rdx-utils";
|
||
|
|
|
||
|
|
import type { PrinterConfiguration } from "../domain/printer-configuration.aggregate";
|
||
|
|
import {
|
||
|
|
PrinterConfigurationError,
|
||
|
|
type PrinterConfigurationInput,
|
||
|
|
} from "../domain/printer-configuration-values";
|
||
|
|
import { PrinterConfigurationValues } from "../domain/value-objects/printer-configuration-values";
|
||
|
|
|
||
|
|
import type { PrinterContext } from "./printer-configuration.repository";
|
||
|
|
import { printerAvailable, printerReferences } from "./printer-configuration-policy";
|
||
|
|
export function mapPrinterInput(
|
||
|
|
input: PrinterConfigurationInput,
|
||
|
|
context: PrinterContext,
|
||
|
|
previous?: PrinterConfiguration
|
||
|
|
) {
|
||
|
|
const parsed = PrinterConfigurationValues.create(input);
|
||
|
|
if (!parsed.isSuccess) {
|
||
|
|
return parsed;
|
||
|
|
}
|
||
|
|
const values = parsed.data;
|
||
|
|
if (previous && !previous.values.sameTarget(values)) {
|
||
|
|
return Result.fail(new PrinterConfigurationError("PRINTER_TARGET_IMMUTABLE"));
|
||
|
|
}
|
||
|
|
if (!printerReferences(values, context)) {
|
||
|
|
return Result.fail(new PrinterConfigurationError("PRINTER_REFERENCE_NOT_FOUND"));
|
||
|
|
}
|
||
|
|
const reconfiguring =
|
||
|
|
!previous ||
|
||
|
|
previous.values.state !== values.state ||
|
||
|
|
previous.values.connection !== values.connection ||
|
||
|
|
(!previous.values.isDefault && values.isDefault);
|
||
|
|
if (
|
||
|
|
["pending", "configured"].includes(values.state) &&
|
||
|
|
reconfiguring &&
|
||
|
|
!printerAvailable(values, context)
|
||
|
|
) {
|
||
|
|
return Result.fail(new PrinterConfigurationError("PRINTER_REFERENCE_UNAVAILABLE"));
|
||
|
|
}
|
||
|
|
const others = context.configurations.filter(
|
||
|
|
(item) => !(item.id.equals(previous?.id) || item.values.closed)
|
||
|
|
);
|
||
|
|
if (!values.closed && others.some((item) => item.values.sameTarget(values))) {
|
||
|
|
return Result.fail(new PrinterConfigurationError("PRINTER_ALREADY_OPEN"));
|
||
|
|
}
|
||
|
|
if (
|
||
|
|
values.isDefault &&
|
||
|
|
others.some((item) => item.values.isDefault && item.values.profileId.equals(values.profileId))
|
||
|
|
) {
|
||
|
|
return Result.fail(new PrinterConfigurationError("DEFAULT_PRINTER_EXISTS"));
|
||
|
|
}
|
||
|
|
return parsed;
|
||
|
|
}
|