metis-desk/modules/resources/src/api/application/resource-inventory.service.ts

70 lines
2.2 KiB
TypeScript
Raw Normal View History

import type { UniqueID } from "@repo/rdx-ddd";
import type { ResourceDefinitionSpec } from "../domain/resource-definition";
import type { IResourceRepository } from "./resource.repository";
2026-10-10 10:01:58 +00:00
export interface IResourceInventoryService {
list(company: UniqueID): Promise<
readonly {
id: UniqueID;
name: string;
active: boolean;
usage: "application" | "certificate" | "support" | "os" | "license" | null;
expiresOn: string | null;
}[]
>;
}
2026-10-10 10:01:58 +00:00
export class ResourceInventoryService implements IResourceInventoryService {
constructor(private readonly repository: IResourceRepository) {}
2026-10-10 10:01:58 +00:00
async list(company: UniqueID) {
const result = await this.repository.get(company);
2026-10-10 10:01:58 +00:00
if (!result.isSuccess) {
throw new Error("No se pudo consultar el inventario de recursos.");
}
const expiryFieldId = result.data.catalog.definitions
.find((item) => item.stockKey.getOrUndefined() === "field:expires")
?.id.toPrimitive();
2026-10-10 10:01:58 +00:00
return result.data.resources.map((resource) => {
const template = result.data.catalog.definitions.find(
(item) => item.id.toPrimitive() === resource.values.toPrimitive().templateId
);
const data = template?.values.data;
const key = template?.stockKey.getOrUndefined();
const usage = resourceUsage(key, data);
const expiresOn = expiryFieldId
? resource.values.toPrimitive().characteristics[expiryFieldId]
: null;
2026-10-10 10:01:58 +00:00
return {
id: resource.id,
name: resource.values.toPrimitive().name,
active: resource.values.toPrimitive().active,
usage,
expiresOn: typeof expiresOn === "string" ? expiresOn : null,
};
});
}
}
function resourceUsage(key: string | undefined, definition: ResourceDefinitionSpec | undefined) {
switch (key) {
case "template:application":
return "application";
case "template:certificate":
return "certificate";
case "template:software_license":
return "license";
case "template:os":
return "os";
case "template:support":
return "support";
default:
return definition?.kind === "template" ? (definition.usage ?? null) : null;
}
}