61 lines
2.2 KiB
TypeScript
61 lines
2.2 KiB
TypeScript
|
|
import type { UniqueID } from "@repo/rdx-ddd";
|
||
|
|
import { Maybe, Result } from "@repo/rdx-utils";
|
||
|
|
|
||
|
|
import type { Resource } from "../domain/resource.aggregate";
|
||
|
|
import { ResourceCatalogError } from "../domain/resource-definition";
|
||
|
|
import type { ResourceInput } from "../domain/resource-values";
|
||
|
|
import { ResourceSpecification, ResourceValues } from "../domain/value-objects/resource-values";
|
||
|
|
|
||
|
|
import type { InventoryContext } from "./resource.repository";
|
||
|
|
|
||
|
|
export function mapResourceInput(
|
||
|
|
input: ResourceInput,
|
||
|
|
companyId: UniqueID,
|
||
|
|
context: InventoryContext,
|
||
|
|
previous?: Resource
|
||
|
|
) {
|
||
|
|
if (previous && previous.values.toPrimitive().templateId !== input.templateId.toLowerCase()) {
|
||
|
|
return Result.fail(new ResourceCatalogError("TEMPLATE_FIXED"));
|
||
|
|
}
|
||
|
|
let specification = previous?.specification;
|
||
|
|
if (!specification) {
|
||
|
|
const template = context.catalog
|
||
|
|
.visible(Maybe.some(companyId))
|
||
|
|
.find((item) => item.id.toPrimitive() === input.templateId.toLowerCase());
|
||
|
|
if (
|
||
|
|
!template ||
|
||
|
|
template.values.data.kind !== "template" ||
|
||
|
|
!context.catalog.active(template, Maybe.some(companyId))
|
||
|
|
) {
|
||
|
|
return Result.fail(new ResourceCatalogError("TEMPLATE_UNAVAILABLE"));
|
||
|
|
}
|
||
|
|
const fields = template.values.data.fields.map((binding) => {
|
||
|
|
const field = context.catalog.definitions.find(
|
||
|
|
(item) => item.id.toPrimitive() === binding.fieldId
|
||
|
|
);
|
||
|
|
if (!field || field.values.data.kind !== "field") {
|
||
|
|
throw new Error("Plantilla persistida inconsistente.");
|
||
|
|
}
|
||
|
|
return {
|
||
|
|
fieldId: field.id.toPrimitive(),
|
||
|
|
name: field.values.data.name,
|
||
|
|
type: field.values.data.type,
|
||
|
|
unit: field.values.data.unit,
|
||
|
|
choices: [...field.values.data.choices],
|
||
|
|
required: binding.required,
|
||
|
|
};
|
||
|
|
});
|
||
|
|
const created = ResourceSpecification.create({
|
||
|
|
templateId: template.id.toPrimitive(),
|
||
|
|
templateName: template.values.data.name,
|
||
|
|
fields,
|
||
|
|
});
|
||
|
|
if (!created.isSuccess) {
|
||
|
|
return created;
|
||
|
|
}
|
||
|
|
specification = created.data;
|
||
|
|
}
|
||
|
|
const values = ResourceValues.create(input, specification);
|
||
|
|
return values.isSuccess ? Result.ok({ specification, values: values.data }) : values;
|
||
|
|
}
|