forked from jappel/leistungsbilanz-ts
314 lines
11 KiB
TypeScript
314 lines
11 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import type { Request, Response } from "express";
|
|
import { createProjectDeviceUpdateProjectCommand } from "../../domain/models/project-device-project-command.model.js";
|
|
import {
|
|
createProjectDeviceDeleteProjectCommand,
|
|
createProjectDeviceInsertProjectCommand,
|
|
type ProjectDeviceSnapshot,
|
|
} from "../../domain/models/project-device-structure-project-command.model.js";
|
|
import { projectDeviceSyncService } from "../composition/project-device-sync-service.js";
|
|
import { projectCommandService } from "../composition/project-command-stores.js";
|
|
import {
|
|
globalDeviceRepository,
|
|
projectDeviceRepository,
|
|
projectRepository,
|
|
} from "../composition/application-repositories.js";
|
|
import {
|
|
createProjectDeviceCommandSchema,
|
|
disconnectProjectDeviceRowsSchema,
|
|
projectDeviceStructureCommandSchema,
|
|
synchronizeProjectDeviceRowsSchema,
|
|
updateProjectDeviceCommandSchema,
|
|
} from "../../shared/validation/project-device.schemas.js";
|
|
import type { CreateProjectDeviceInput } from "../../shared/validation/project-device.schemas.js";
|
|
import { respondWithProjectCommandError } from "./project-command.controller.js";
|
|
import { resolveProjectVoltage } from "../../domain/services/project-voltage.service.js";
|
|
import { resolveProjectDevicePhaseType } from "../../domain/services/project-device-placement.service.js";
|
|
import type { CircuitGroupCategory } from "../../shared/constants/circuit-group.js";
|
|
|
|
export async function listProjectDevicesByProject(req: Request, res: Response) {
|
|
const { projectId } = req.params;
|
|
if (typeof projectId !== "string") {
|
|
return res.status(400).json({ error: "Invalid projectId" });
|
|
}
|
|
const rows = await projectDeviceRepository.listByProject(projectId);
|
|
return res.json(rows);
|
|
}
|
|
|
|
export async function createProjectDevice(req: Request, res: Response) {
|
|
const { projectId } = req.params;
|
|
if (typeof projectId !== "string") {
|
|
return res.status(400).json({ error: "Invalid projectId" });
|
|
}
|
|
const parsed = createProjectDeviceCommandSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: parsed.error.flatten() });
|
|
}
|
|
const { expectedRevision, ...input } = parsed.data;
|
|
|
|
try {
|
|
const project = await projectRepository.findById(projectId);
|
|
if (!project) {
|
|
return res.status(404).json({ error: "Project not found" });
|
|
}
|
|
const projectDevice = toProjectDeviceSnapshot(
|
|
projectId,
|
|
randomUUID(),
|
|
input,
|
|
project
|
|
);
|
|
const result = projectCommandService.executeUser({
|
|
projectId,
|
|
expectedRevision,
|
|
description: "Projektgerät anlegen",
|
|
command: createProjectDeviceInsertProjectCommand(projectDevice),
|
|
});
|
|
const created = await projectDeviceRepository.findById(projectId, projectDevice.id);
|
|
if (!created) {
|
|
throw new Error("Created project device could not be loaded.");
|
|
}
|
|
return res.status(201).json({ ...result, projectDevice: created });
|
|
} catch (error) {
|
|
return respondWithProjectCommandError(error, res);
|
|
}
|
|
}
|
|
|
|
export async function updateProjectDevice(req: Request, res: Response) {
|
|
const { projectId, projectDeviceId } = req.params;
|
|
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
|
return res.status(400).json({ error: "Invalid parameters" });
|
|
}
|
|
|
|
const parsed = updateProjectDeviceCommandSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: parsed.error.flatten() });
|
|
}
|
|
const { expectedRevision, ...input } = parsed.data;
|
|
|
|
try {
|
|
const project = await projectRepository.findById(projectId);
|
|
if (!project) {
|
|
return res.status(404).json({ error: "Project not found" });
|
|
}
|
|
const result = projectCommandService.executeUser({
|
|
projectId,
|
|
expectedRevision,
|
|
description: "Projektgerät bearbeiten",
|
|
command: createProjectDeviceUpdateProjectCommand(
|
|
projectDeviceId,
|
|
toProjectDeviceValues(input, project)
|
|
),
|
|
});
|
|
// Linked rows are synchronized only through the explicit review flow.
|
|
// Updating a project device must never silently overwrite local circuit-list values.
|
|
const projectDevice = await projectDeviceRepository.findById(projectId, projectDeviceId);
|
|
if (!projectDevice) {
|
|
throw new Error("Updated project device could not be loaded.");
|
|
}
|
|
return res.json({ ...result, projectDevice });
|
|
} catch (error) {
|
|
return respondWithProjectCommandError(error, res);
|
|
}
|
|
}
|
|
|
|
export async function deleteProjectDevice(req: Request, res: Response) {
|
|
const { projectId, projectDeviceId } = req.params;
|
|
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
|
return res.status(400).json({ error: "Invalid parameters" });
|
|
}
|
|
|
|
const parsed = projectDeviceStructureCommandSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: parsed.error.flatten() });
|
|
}
|
|
|
|
try {
|
|
return res.json(
|
|
projectCommandService.executeUser({
|
|
projectId,
|
|
expectedRevision: parsed.data.expectedRevision,
|
|
description: "Projektgerät löschen",
|
|
command: createProjectDeviceDeleteProjectCommand(projectDeviceId, projectId),
|
|
})
|
|
);
|
|
} catch (error) {
|
|
return respondWithProjectCommandError(error, res);
|
|
}
|
|
}
|
|
|
|
export async function copyGlobalDeviceToProject(req: Request, res: Response) {
|
|
const { projectId, globalDeviceId } = req.params;
|
|
if (typeof projectId !== "string" || typeof globalDeviceId !== "string") {
|
|
return res.status(400).json({ error: "Invalid parameters" });
|
|
}
|
|
const parsed = projectDeviceStructureCommandSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: parsed.error.flatten() });
|
|
}
|
|
|
|
const source = await globalDeviceRepository.findById(globalDeviceId);
|
|
if (!source) {
|
|
return res.status(404).json({ error: "Global device not found" });
|
|
}
|
|
const project = await projectRepository.findById(projectId);
|
|
if (!project) {
|
|
return res.status(404).json({ error: "Project not found" });
|
|
}
|
|
|
|
const projectDevice = toProjectDeviceSnapshot(projectId, randomUUID(), {
|
|
name: source.name,
|
|
displayName: source.displayName,
|
|
category: inferImportedProjectDeviceCategory(
|
|
source.category,
|
|
source.phaseCount
|
|
),
|
|
quantity: source.quantity,
|
|
powerPerUnit: source.installedPowerPerUnitKw,
|
|
simultaneityFactor: source.demandFactor,
|
|
cosPhi: source.powerFactor ?? undefined,
|
|
remark: source.note ?? undefined,
|
|
}, project);
|
|
|
|
try {
|
|
const result = projectCommandService.executeUser({
|
|
projectId,
|
|
expectedRevision: parsed.data.expectedRevision,
|
|
description: "Globales Gerät ins Projekt übernehmen",
|
|
command: createProjectDeviceInsertProjectCommand(projectDevice),
|
|
});
|
|
const created = await projectDeviceRepository.findById(projectId, projectDevice.id);
|
|
if (!created) {
|
|
throw new Error("Imported project device could not be loaded.");
|
|
}
|
|
return res.status(201).json({ ...result, projectDevice: created });
|
|
} catch (error) {
|
|
return respondWithProjectCommandError(error, res);
|
|
}
|
|
}
|
|
|
|
function toProjectDeviceSnapshot(
|
|
projectId: string,
|
|
id: string,
|
|
input: CreateProjectDeviceInput,
|
|
project: {
|
|
singlePhaseVoltageV: number;
|
|
threePhaseVoltageV: number;
|
|
}
|
|
): ProjectDeviceSnapshot {
|
|
return {
|
|
id,
|
|
projectId,
|
|
...toProjectDeviceValues(input, project),
|
|
};
|
|
}
|
|
|
|
function toProjectDeviceValues(
|
|
input: CreateProjectDeviceInput,
|
|
project: {
|
|
singlePhaseVoltageV: number;
|
|
threePhaseVoltageV: number;
|
|
}
|
|
) {
|
|
const phaseType = resolveProjectDevicePhaseType(input.category);
|
|
return {
|
|
name: input.name,
|
|
displayName: input.displayName,
|
|
phaseType,
|
|
connectionKind: input.connectionKind ?? null,
|
|
costGroup: input.costGroup ?? null,
|
|
category: input.category,
|
|
quantity: input.quantity,
|
|
powerPerUnit: input.powerPerUnit,
|
|
simultaneityFactor: input.simultaneityFactor,
|
|
cosPhi: input.cosPhi ?? null,
|
|
remark: input.remark ?? null,
|
|
voltageV: resolveProjectVoltage(phaseType, project),
|
|
};
|
|
}
|
|
|
|
function inferImportedProjectDeviceCategory(
|
|
category: string | null,
|
|
phaseCount: number | null
|
|
): CircuitGroupCategory {
|
|
const normalized = category?.trim().toLowerCase() ?? "";
|
|
if (normalized.includes("light") || normalized.includes("beleuchtung")) {
|
|
return "lighting";
|
|
}
|
|
return phaseCount === 3 ? "three_phase" : "single_phase";
|
|
}
|
|
|
|
export async function getProjectDeviceSyncPreview(req: Request, res: Response) {
|
|
const { projectId, projectDeviceId } = req.params;
|
|
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
|
return res.status(400).json({ error: "Invalid parameters" });
|
|
}
|
|
try {
|
|
const preview = await projectDeviceSyncService.getPreview(projectId, projectDeviceId);
|
|
return res.json(preview);
|
|
} catch (error) {
|
|
return res.status(400).json({ error: error instanceof Error ? error.message : "Failed to load sync preview." });
|
|
}
|
|
}
|
|
|
|
export async function synchronizeProjectDeviceRows(req: Request, res: Response) {
|
|
const { projectId, projectDeviceId } = req.params;
|
|
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
|
return res.status(400).json({ error: "Invalid parameters" });
|
|
}
|
|
const parsed = synchronizeProjectDeviceRowsSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: parsed.error.flatten() });
|
|
}
|
|
try {
|
|
const command = await projectDeviceSyncService.createSynchronizeCommand(
|
|
projectId,
|
|
projectDeviceId,
|
|
parsed.data.rowIds,
|
|
parsed.data.fields
|
|
);
|
|
const result = projectCommandService.executeUser({
|
|
projectId,
|
|
expectedRevision: parsed.data.expectedRevision,
|
|
description: "Projektgerät in Stromkreiszeilen synchronisieren",
|
|
command,
|
|
});
|
|
const preview = await projectDeviceSyncService.getPreview(
|
|
projectId,
|
|
projectDeviceId
|
|
);
|
|
return res.json({ ...result, preview });
|
|
} catch (error) {
|
|
return respondWithProjectCommandError(error, res);
|
|
}
|
|
}
|
|
|
|
export async function disconnectProjectDeviceRows(req: Request, res: Response) {
|
|
const { projectId, projectDeviceId } = req.params;
|
|
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
|
return res.status(400).json({ error: "Invalid parameters" });
|
|
}
|
|
const parsed = disconnectProjectDeviceRowsSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: parsed.error.flatten() });
|
|
}
|
|
try {
|
|
const command = await projectDeviceSyncService.createDisconnectCommand(
|
|
projectId,
|
|
projectDeviceId,
|
|
parsed.data.rowIds
|
|
);
|
|
const result = projectCommandService.executeUser({
|
|
projectId,
|
|
expectedRevision: parsed.data.expectedRevision,
|
|
description: "Projektgerät-Verknüpfungen trennen",
|
|
command,
|
|
});
|
|
const preview = await projectDeviceSyncService.getPreview(
|
|
projectId,
|
|
projectDeviceId
|
|
);
|
|
return res.json({ ...result, preview });
|
|
} catch (error) {
|
|
return respondWithProjectCommandError(error, res);
|
|
}
|
|
}
|