65 lines
1.8 KiB
TypeScript
65 lines
1.8 KiB
TypeScript
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.`);
|
||
}
|