Protect referenced feeder structures from deletion

This commit is contained in:
Julian Appel 2026-09-27 22:25:47 +02:00
parent b893c72534
commit 855a04e655
13 changed files with 369 additions and 0 deletions

View file

@ -0,0 +1,65 @@
import { and, asc, eq, inArray } from "drizzle-orm";
import type { AppDatabase } from "../database-context.js";
import { distributionBoards } from "../schema/distribution-boards.js";
export function assertBoardsAreNotReferencedAsFeeders(
database: AppDatabase,
projectId: string,
distributionBoardIds: string[]
) {
if (distributionBoardIds.length === 0) return;
const dependent = database
.select({
name: distributionBoards.name,
boardNumber: distributionBoards.boardNumber,
})
.from(distributionBoards)
.where(
and(
eq(distributionBoards.projectId, projectId),
inArray(
distributionBoards.feedingDistributionBoardId,
[...new Set(distributionBoardIds)]
)
)
)
.orderBy(asc(distributionBoards.boardNumber), asc(distributionBoards.name))
.limit(1)
.get();
if (dependent) throwFeedingReferenceError(dependent);
}
export function assertCircuitsAreNotReferencedAsFeeders(
database: AppDatabase,
projectId: string,
circuitIds: string[]
) {
if (circuitIds.length === 0) return;
const dependent = database
.select({
name: distributionBoards.name,
boardNumber: distributionBoards.boardNumber,
})
.from(distributionBoards)
.where(
and(
eq(distributionBoards.projectId, projectId),
inArray(
distributionBoards.feedingCircuitId,
[...new Set(circuitIds)]
)
)
)
.orderBy(asc(distributionBoards.boardNumber), asc(distributionBoards.name))
.limit(1)
.get();
if (dependent) throwFeedingReferenceError(dependent);
}
function throwFeedingReferenceError(dependent: {
name: string;
boardNumber: string | null;
}): never {
const label = dependent.boardNumber ?? dependent.name;
throw new Error(`Speist ${label} – erst Einspeisung ändern.`);
}