Files
leistungsbilanz-ts/src/server/controllers/global-device.controller.ts
T
2026-05-01 17:58:14 +02:00

82 lines
2.9 KiB
TypeScript

import type { Request, Response } from "express";
import { GlobalDeviceRepository } from "../../db/repositories/global-device.repository.js";
import { ProjectDeviceRepository } from "../../db/repositories/project-device.repository.js";
import {
createGlobalDeviceSchema,
updateGlobalDeviceSchema,
} from "../../shared/validation/global-device.schemas.js";
const globalDeviceRepository = new GlobalDeviceRepository();
const projectDeviceRepository = new ProjectDeviceRepository();
export async function listGlobalDevices(_req: Request, res: Response) {
const rows = await globalDeviceRepository.list();
return res.json(rows);
}
export async function createGlobalDevice(req: Request, res: Response) {
const parsed = createGlobalDeviceSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: parsed.error.flatten() });
}
const created = await globalDeviceRepository.create(parsed.data);
return res.status(201).json(created);
}
export async function updateGlobalDevice(req: Request, res: Response) {
const { globalDeviceId } = req.params;
if (typeof globalDeviceId !== "string") {
return res.status(400).json({ error: "Invalid globalDeviceId" });
}
const parsed = updateGlobalDeviceSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: parsed.error.flatten() });
}
await globalDeviceRepository.update(globalDeviceId, parsed.data);
const row = await globalDeviceRepository.findById(globalDeviceId);
if (!row) {
return res.status(404).json({ error: "Global device not found" });
}
return res.json(row);
}
export async function deleteGlobalDevice(req: Request, res: Response) {
const { globalDeviceId } = req.params;
if (typeof globalDeviceId !== "string") {
return res.status(400).json({ error: "Invalid globalDeviceId" });
}
await globalDeviceRepository.delete(globalDeviceId);
return res.status(204).send();
}
export async function copyProjectDeviceToGlobal(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 source = await projectDeviceRepository.findById(projectId, projectDeviceId);
if (!source) {
return res.status(404).json({ error: "Project device not found" });
}
const created = await globalDeviceRepository.create({
name: source.name,
displayName: source.displayName,
category: source.category ?? undefined,
quantity: source.quantity,
installedPowerPerUnitKw: source.installedPowerPerUnitKw,
demandFactor: source.demandFactor,
voltageV: source.voltageV ?? undefined,
phaseCount: source.phaseCount === 1 || source.phaseCount === 3 ? source.phaseCount : undefined,
powerFactor: source.powerFactor ?? undefined,
note: source.note ?? undefined,
});
return res.status(201).json(created);
}