Add external object new row command

This commit is contained in:
2026-08-02 18:44:46 +02:00
parent 1a7dd7fe03
commit 347b3717c3
10 changed files with 649 additions and 9 deletions
@@ -0,0 +1,266 @@
import { and, eq, inArray, isNull } from "drizzle-orm";
import { assertCircuitDeviceRowQuantity } from "../../domain/calculations/circuit-device-row-quantity.js";
import {
assertExternalObjectNewRowProjectCommand,
externalObjectAssignToNewRowCommandType,
externalObjectDeleteCreatedRowCommandType,
invertExternalObjectNewRowProjectCommand,
type ExternalObjectNewRowProjectCommand,
} from "../../domain/models/external-object-new-row-project-command.model.js";
import type { CircuitDeviceRowSnapshot } from "../../domain/models/circuit-device-row-structure-project-command.model.js";
import type { ExternalObjectNewRowProjectCommandStore } from "../../domain/ports/external-object-new-row-project-command.store.js";
import { isElectricalPhaseType } from "../../domain/services/project-voltage.service.js";
import type { ExternalModelObjectSnapshot } from "../../external-model/domain/external-model-contracts.js";
import type { AppDatabase } from "../database-context.js";
import { circuitDeviceRows } from "../schema/circuit-device-rows.js";
import { circuitLists } from "../schema/circuit-lists.js";
import { circuitSections } from "../schema/circuit-sections.js";
import { circuits } from "../schema/circuits.js";
import { externalModelObjects } from "../schema/external-model-objects.js";
import { externalRoomMappings } from "../schema/external-room-mappings.js";
import {
assertCircuitDeviceRowReferencesInProject,
toCircuitDeviceRowInsertValues,
toCircuitDeviceRowSnapshot,
} from "./circuit-device-row-structure.persistence.js";
import { executeProjectCommandTransaction } from "./project-command-transaction.persistence.js";
import { updateDerivedCircuitVoltage } from "./project-voltage.persistence.js";
export class ExternalObjectNewRowProjectCommandRepository
implements ExternalObjectNewRowProjectCommandStore
{
constructor(private readonly database: AppDatabase) {}
execute(input: Parameters<ExternalObjectNewRowProjectCommandStore["execute"]>[0]) {
assertExternalObjectNewRowProjectCommand(input.command);
if (
input.source === "user" &&
input.command.type === externalObjectDeleteCreatedRowCommandType
) {
throw new Error("Created external rows may only be removed through project history.");
}
return executeProjectCommandTransaction(this.database, input, (tx) => {
if (input.command.type === externalObjectAssignToNewRowCommandType) {
this.insert(tx, input.projectId, input.command);
} else {
this.remove(tx, input.projectId, input.command);
}
return invertExternalObjectNewRowProjectCommand(input.command);
});
}
private insert(
database: AppDatabase,
projectId: string,
command: ExternalObjectNewRowProjectCommand
) {
const row = command.payload.row;
const context = this.loadCircuitContext(database, projectId, row.circuitId);
if (!isElectricalPhaseType(row.phaseType)) {
throw new Error("External device-row phase type is invalid.");
}
if (row.category !== context.category) {
throw new Error("External device-row category does not match target circuit group.");
}
assertCircuitDeviceRowReferencesInProject(database, projectId, row);
if (database.select({ id: circuitDeviceRows.id }).from(circuitDeviceRows)
.where(eq(circuitDeviceRows.id, row.id)).get()) {
throw new Error("External device-row id already exists.");
}
const objects = this.loadExpectedObjects(database, projectId, command);
this.assertTargetCompatibility(
database,
row,
context.distributionBoardId,
context.category,
objects.map((object) => object.target),
new Set(command.payload.confirmedConflictObjectIds)
);
assertCircuitDeviceRowQuantity({
quantity: row.quantity,
manualQuantity: 0,
externalObjects: objects.map(({ target }) => ({
effectiveQuantity: target.planningValues.effectiveQuantity,
})),
});
database.insert(circuitDeviceRows).values(toCircuitDeviceRowInsertValues(row)).run();
this.updateCircuitState(database, projectId, row.circuitId);
this.applyObjectLinks(database, objects);
}
private remove(
database: AppDatabase,
projectId: string,
command: ExternalObjectNewRowProjectCommand
) {
const expectedRow = command.payload.row;
this.loadCircuitContext(database, projectId, expectedRow.circuitId);
const currentRow = database.select().from(circuitDeviceRows)
.where(eq(circuitDeviceRows.id, expectedRow.id)).get();
if (!currentRow || !same(toCircuitDeviceRowSnapshot(currentRow), expectedRow)) {
throw new Error("Created external device row changed before history removal.");
}
const objects = this.loadExpectedObjects(database, projectId, command);
const linkedObjects = database.select({ id: externalModelObjects.id })
.from(externalModelObjects)
.where(eq(externalModelObjects.circuitDeviceRowId, expectedRow.id)).all();
if (
linkedObjects.length !== objects.length ||
linkedObjects.some(({ id }) => !objects.some((object) => object.expected.id === id))
) {
throw new Error("Created external device row has different object links.");
}
this.applyObjectLinks(database, objects);
const deleted = database.delete(circuitDeviceRows)
.where(eq(circuitDeviceRows.id, expectedRow.id)).run();
if (deleted.changes !== 1) {
throw new Error("Created external device row changed during history removal.");
}
this.updateCircuitState(database, projectId, expectedRow.circuitId);
}
private loadCircuitContext(database: AppDatabase, projectId: string, circuitId: string) {
const context = database.select({
projectId: circuitLists.projectId,
distributionBoardId: circuitLists.distributionBoardId,
category: circuitSections.category,
}).from(circuits)
.innerJoin(circuitLists, eq(circuitLists.id, circuits.circuitListId))
.innerJoin(circuitSections, eq(circuitSections.id, circuits.sectionId))
.where(eq(circuits.id, circuitId)).get();
if (!context || context.projectId !== projectId || context.category === null) {
throw new Error("Target circuit does not belong to the project.");
}
return {
projectId: context.projectId,
distributionBoardId: context.distributionBoardId,
category: context.category,
};
}
private loadExpectedObjects(
database: AppDatabase,
projectId: string,
command: ExternalObjectNewRowProjectCommand
) {
const transitions = new Map(
command.payload.objects.map((transition) => [transition.expected.id, transition])
);
const current = database.select().from(externalModelObjects)
.where(inArray(externalModelObjects.id, [...transitions.keys()])).all();
if (current.length !== transitions.size) {
throw new Error("One or more external objects no longer exist.");
}
for (const object of current) {
const expected = transitions.get(object.id)!.expected;
if (object.projectId !== projectId || !same(toExternalObjectSnapshot(object), expected)) {
throw new Error("External object changed before new-row assignment.");
}
}
return command.payload.objects;
}
private assertTargetCompatibility(
database: AppDatabase,
row: CircuitDeviceRowSnapshot,
distributionBoardId: string,
category: string,
objects: ExternalModelObjectSnapshot[],
confirmedConflicts: Set<string>
) {
const roomMappings = database.select().from(externalRoomMappings)
.where(eq(externalRoomMappings.projectId, objects[0]!.projectId)).all();
const roomIdByMappingId = new Map(roomMappings.map((mapping) => [mapping.id, mapping.roomId]));
const selectionMarkers = new Set(
objects.map((object) => object.acceptedSourceValues.selectionMarker.trim())
);
if (selectionMarkers.size > 1) {
throw new Error("External objects with different selection markers require separate rows.");
}
for (const object of objects) {
if (object.distributionBoardId !== distributionBoardId) {
throw new Error("External object distribution does not match target circuit.");
}
if (object.planningValues.category !== category) {
throw new Error("External object category does not match target circuit group.");
}
const objectRoomId = object.externalRoomMappingId === null
? null
: roomIdByMappingId.get(object.externalRoomMappingId) ?? null;
if (objectRoomId !== row.roomId) {
throw new Error("External object room does not match the new device row.");
}
if (!matchesRowPlanningValues(row, object) && !confirmedConflicts.has(object.id)) {
throw new Error("External object planning values require explicit conflict confirmation.");
}
}
}
private applyObjectLinks(
database: AppDatabase,
objects: ExternalObjectNewRowProjectCommand["payload"]["objects"]
) {
for (const { expected, target } of objects) {
const result = database.update(externalModelObjects)
.set({ circuitDeviceRowId: target.circuitDeviceRowId })
.where(and(
eq(externalModelObjects.id, expected.id),
expected.circuitDeviceRowId === null
? isNull(externalModelObjects.circuitDeviceRowId)
: eq(externalModelObjects.circuitDeviceRowId, expected.circuitDeviceRowId)
)).run();
if (result.changes !== 1) {
throw new Error("External object changed during new-row assignment.");
}
}
}
private updateCircuitState(database: AppDatabase, projectId: string, circuitId: string) {
const remaining = database.select({ id: circuitDeviceRows.id }).from(circuitDeviceRows)
.where(eq(circuitDeviceRows.circuitId, circuitId)).limit(1).get();
const result = database.update(circuits).set({ isReserve: remaining ? 0 : 1 })
.where(eq(circuits.id, circuitId)).run();
if (result.changes !== 1) throw new Error("Target circuit changed during row assignment.");
updateDerivedCircuitVoltage(database, projectId, circuitId);
}
}
function matchesRowPlanningValues(
row: CircuitDeviceRowSnapshot,
object: ExternalModelObjectSnapshot
) {
const planning = object.planningValues;
return (
row.displayName === (planning.displayName ?? row.displayName) &&
row.linkedProjectDeviceId === object.linkedProjectDeviceId &&
row.category === planning.category &&
row.connectionKind === planning.connectionKind &&
(planning.powerPerUnitW === null || row.powerPerUnit === planning.powerPerUnitW / 1000) &&
row.simultaneityFactor === planning.simultaneityFactor &&
row.cosPhi === planning.cosPhi &&
row.costGroup === planning.costGroup &&
row.remark === planning.remark
);
}
function toExternalObjectSnapshot(
object: typeof externalModelObjects.$inferSelect
): ExternalModelObjectSnapshot {
return { ...object };
}
function same(left: unknown, right: unknown) {
return canonicalJson(left) === canonicalJson(right);
}
function canonicalJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
if (value !== null && typeof value === "object") {
const record = value as Record<string, unknown>;
return `{${Object.keys(record).sort().map((key) =>
`${JSON.stringify(key)}:${canonicalJson(record[key])}`
).join(",")}}`;
}
return JSON.stringify(value);
}