leistungsbilanz-ts/src/db/repositories/distribution-board-feeding-deletion-guard.persistence.ts

65 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.`);
}