Add project device sync history

This commit is contained in:
2026-07-24 08:47:25 +02:00
parent 4b4603b71b
commit 2668fc2f16
14 changed files with 1180 additions and 21 deletions
@@ -0,0 +1,151 @@
import { and, eq, inArray } from "drizzle-orm";
import {
assertProjectDeviceRowSyncProjectCommand,
createProjectDeviceRowSyncProjectCommand,
invertProjectDeviceRowSyncOperation,
projectDeviceSyncRowSnapshotFields,
type ProjectDeviceSyncRowSnapshot,
} from "../../domain/models/project-device-row-sync-project-command.model.js";
import type {
ExecuteProjectDeviceRowSyncCommandInput,
ProjectDeviceRowSyncProjectCommandStore,
} from "../../domain/ports/project-device-row-sync-project-command.store.js";
import type { AppDatabase } from "../database-context.js";
import { circuitDeviceRows } from "../schema/circuit-device-rows.js";
import { circuitLists } from "../schema/circuit-lists.js";
import { circuits } from "../schema/circuits.js";
import { projectDevices } from "../schema/project-devices.js";
import { applyProjectHistoryTransition } from "./project-history.persistence.js";
import { appendProjectRevision } from "./project-revision.persistence.js";
type CircuitDeviceRow = typeof circuitDeviceRows.$inferSelect;
export class ProjectDeviceRowSyncProjectCommandRepository
implements ProjectDeviceRowSyncProjectCommandStore
{
constructor(private readonly database: AppDatabase) {}
execute(input: ExecuteProjectDeviceRowSyncCommandInput) {
assertProjectDeviceRowSyncProjectCommand(input.command);
return this.database.transaction((tx) => {
const projectDevice = tx
.select({ id: projectDevices.id })
.from(projectDevices)
.where(
and(
eq(
projectDevices.id,
input.command.payload.projectDeviceId
),
eq(projectDevices.projectId, input.projectId)
)
)
.get();
if (!projectDevice) {
throw new Error(
"Project device does not belong to project."
);
}
const rowIds = input.command.payload.rows.map(
(row) => row.rowId
);
const persistedRows = tx
.select({
row: circuitDeviceRows,
projectId: circuitLists.projectId,
})
.from(circuitDeviceRows)
.innerJoin(
circuits,
eq(circuits.id, circuitDeviceRows.circuitId)
)
.innerJoin(
circuitLists,
eq(circuitLists.id, circuits.circuitListId)
)
.where(inArray(circuitDeviceRows.id, rowIds))
.all();
if (
persistedRows.length !== rowIds.length ||
persistedRows.some(
(persisted) => persisted.projectId !== input.projectId
)
) {
throw new Error(
"One or more sync rows do not belong to project."
);
}
const persistedById = new Map(
persistedRows.map((persisted) => [
persisted.row.id,
persisted.row,
])
);
for (const assignment of input.command.payload.rows) {
const persisted = persistedById.get(assignment.rowId);
if (
!persisted ||
!snapshotMatchesRow(assignment.expected, persisted)
) {
throw new Error(
"Project-device row changed before sync execution."
);
}
}
const inverse = createProjectDeviceRowSyncProjectCommand(
projectDevice.id,
invertProjectDeviceRowSyncOperation(
input.command.payload.operation
),
input.command.payload.rows.map((row) => ({
rowId: row.rowId,
expected: row.target,
target: row.expected,
}))
);
for (const assignment of input.command.payload.rows) {
const updated = tx
.update(circuitDeviceRows)
.set(assignment.target)
.where(eq(circuitDeviceRows.id, assignment.rowId))
.run();
if (updated.changes !== 1) {
throw new Error(
"Project-device row changed during sync execution."
);
}
}
const revision = appendProjectRevision(tx, {
projectId: input.projectId,
expectedRevision: input.expectedRevision,
source: input.source,
description: input.description,
actorId: input.actorId,
forward: input.command,
inverse,
});
applyProjectHistoryTransition(tx, {
projectId: input.projectId,
source: input.source,
recordedChangeSetId: revision.changeSetId,
targetChangeSetId: input.historyTargetChangeSetId,
});
return { revision, inverse };
});
}
}
function snapshotMatchesRow(
snapshot: ProjectDeviceSyncRowSnapshot,
row: CircuitDeviceRow
) {
return projectDeviceSyncRowSnapshotFields.every(
(field) => snapshot[field] === row[field]
);
}
@@ -0,0 +1,245 @@
import {
assertCircuitDeviceRowUpdateProjectCommand,
circuitDeviceRowUpdateCommandSchemaVersion,
circuitDeviceRowUpdateCommandType,
type CircuitDeviceRowUpdateField,
type CircuitDeviceRowUpdateValues,
} from "./circuit-device-row-project-command.model.js";
import type { SerializedProjectCommand } from "./project-command.model.js";
export const projectDeviceRowSyncCommandType =
"project-device.sync-rows" as const;
export const projectDeviceRowSyncCommandSchemaVersion = 1 as const;
export const projectDeviceSyncRowSnapshotFields = [
"linkedProjectDeviceId",
"name",
"displayName",
"phaseType",
"connectionKind",
"costGroup",
"category",
"quantity",
"powerPerUnit",
"simultaneityFactor",
"cosPhi",
"remark",
"overriddenFields",
] as const satisfies readonly CircuitDeviceRowUpdateField[];
export type ProjectDeviceSyncRowSnapshot = Pick<
CircuitDeviceRowUpdateValues,
(typeof projectDeviceSyncRowSnapshotFields)[number]
>;
export type ProjectDeviceRowSyncOperation =
| "synchronize"
| "disconnect"
| "reconnect";
export interface ProjectDeviceRowSyncAssignment {
rowId: string;
expected: ProjectDeviceSyncRowSnapshot;
target: ProjectDeviceSyncRowSnapshot;
}
export interface ProjectDeviceRowSyncCommandPayload {
projectDeviceId: string;
operation: ProjectDeviceRowSyncOperation;
rows: ProjectDeviceRowSyncAssignment[];
}
export interface ProjectDeviceRowSyncProjectCommand
extends SerializedProjectCommand<ProjectDeviceRowSyncCommandPayload> {
schemaVersion: typeof projectDeviceRowSyncCommandSchemaVersion;
type: typeof projectDeviceRowSyncCommandType;
}
export function createProjectDeviceRowSyncProjectCommand(
projectDeviceId: string,
operation: ProjectDeviceRowSyncOperation,
rows: ProjectDeviceRowSyncAssignment[]
): ProjectDeviceRowSyncProjectCommand {
const command: ProjectDeviceRowSyncProjectCommand = {
schemaVersion: projectDeviceRowSyncCommandSchemaVersion,
type: projectDeviceRowSyncCommandType,
payload: { projectDeviceId, operation, rows },
};
assertProjectDeviceRowSyncProjectCommand(command);
return command;
}
export function assertProjectDeviceRowSyncProjectCommand(
command: SerializedProjectCommand<unknown>
): asserts command is ProjectDeviceRowSyncProjectCommand {
if (
command.schemaVersion !== projectDeviceRowSyncCommandSchemaVersion ||
command.type !== projectDeviceRowSyncCommandType
) {
throw new Error("Unsupported project-device row sync command.");
}
if (!isPlainObject(command.payload)) {
throw new Error(
"Project-device row sync payload must be an object."
);
}
const { projectDeviceId, operation, rows } = command.payload;
assertNonEmptyString(projectDeviceId, "projectDeviceId");
if (
operation !== "synchronize" &&
operation !== "disconnect" &&
operation !== "reconnect"
) {
throw new Error(
"Project-device row sync operation is invalid."
);
}
if (!Array.isArray(rows) || rows.length === 0) {
throw new Error(
"Project-device row sync command requires at least one row."
);
}
const rowIds = new Set<string>();
for (const row of rows) {
if (!isPlainObject(row)) {
throw new Error(
"Project-device row sync command contains an invalid row."
);
}
assertNonEmptyString(row.rowId, "rowId");
if (rowIds.has(row.rowId)) {
throw new Error(
"Project-device row sync command contains duplicate row ids."
);
}
assertProjectDeviceSyncRowSnapshot(row.expected);
assertProjectDeviceSyncRowSnapshot(row.target);
const expected =
row.expected as ProjectDeviceSyncRowSnapshot;
const target = row.target as ProjectDeviceSyncRowSnapshot;
if (snapshotsEqual(expected, target)) {
throw new Error(
"Project-device row sync command contains a no-op row."
);
}
assertOperationTransition(
operation,
projectDeviceId,
expected,
target
);
rowIds.add(row.rowId);
}
}
export function invertProjectDeviceRowSyncOperation(
operation: ProjectDeviceRowSyncOperation
): ProjectDeviceRowSyncOperation {
if (operation === "disconnect") {
return "reconnect";
}
if (operation === "reconnect") {
return "disconnect";
}
return "synchronize";
}
function assertProjectDeviceSyncRowSnapshot(snapshot: unknown) {
if (!isPlainObject(snapshot)) {
throw new Error(
"Project-device sync row snapshot must be an object."
);
}
const snapshotKeys = Object.keys(snapshot);
if (
snapshotKeys.length !== projectDeviceSyncRowSnapshotFields.length ||
projectDeviceSyncRowSnapshotFields.some(
(field) =>
!Object.prototype.hasOwnProperty.call(snapshot, field)
)
) {
throw new Error(
"Project-device sync row snapshot must contain every sync field."
);
}
assertCircuitDeviceRowUpdateProjectCommand({
schemaVersion: circuitDeviceRowUpdateCommandSchemaVersion,
type: circuitDeviceRowUpdateCommandType,
payload: {
rowId: "__sync_snapshot_validation__",
changes: projectDeviceSyncRowSnapshotFields.map((field) => ({
field,
value: snapshot[field],
})),
},
});
}
function assertOperationTransition(
operation: ProjectDeviceRowSyncOperation,
projectDeviceId: string,
expected: ProjectDeviceSyncRowSnapshot,
target: ProjectDeviceSyncRowSnapshot
) {
if (operation === "synchronize") {
if (
expected.linkedProjectDeviceId !== projectDeviceId ||
target.linkedProjectDeviceId !== projectDeviceId
) {
throw new Error(
"Synchronized rows must remain linked to the selected project device."
);
}
return;
}
const expectedLink =
operation === "disconnect" ? projectDeviceId : null;
const targetLink =
operation === "disconnect" ? null : projectDeviceId;
if (
expected.linkedProjectDeviceId !== expectedLink ||
target.linkedProjectDeviceId !== targetLink
) {
throw new Error(
"Project-device link transition does not match the operation."
);
}
if (!snapshotsEqualWithoutLink(expected, target)) {
throw new Error(
"Disconnect and reconnect must not change local row values."
);
}
}
function snapshotsEqual(
left: ProjectDeviceSyncRowSnapshot,
right: ProjectDeviceSyncRowSnapshot
) {
return projectDeviceSyncRowSnapshotFields.every(
(field) => left[field] === right[field]
);
}
function snapshotsEqualWithoutLink(
left: ProjectDeviceSyncRowSnapshot,
right: ProjectDeviceSyncRowSnapshot
) {
return projectDeviceSyncRowSnapshotFields
.filter((field) => field !== "linkedProjectDeviceId")
.every((field) => left[field] === right[field]);
}
function assertNonEmptyString(
value: unknown,
field: string
): asserts value is string {
if (typeof value !== "string" || !value.trim()) {
throw new Error(`${field} must be a non-empty string.`);
}
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -0,0 +1,26 @@
import type { ProjectDeviceRowSyncProjectCommand } from "../models/project-device-row-sync-project-command.model.js";
import type {
AppendedProjectRevision,
ProjectRevisionSource,
} from "./project-revision.store.js";
export interface ExecuteProjectDeviceRowSyncCommandInput {
projectId: string;
expectedRevision: number;
source: ProjectRevisionSource;
description?: string;
actorId?: string;
historyTargetChangeSetId?: string;
command: ProjectDeviceRowSyncProjectCommand;
}
export interface ExecutedProjectDeviceRowSyncCommand {
revision: AppendedProjectRevision;
inverse: ProjectDeviceRowSyncProjectCommand;
}
export interface ProjectDeviceRowSyncProjectCommandStore {
execute(
input: ExecuteProjectDeviceRowSyncCommandInput
): ExecutedProjectDeviceRowSyncCommand;
}
@@ -37,6 +37,10 @@ import {
assertSerializedProjectCommand,
type SerializedProjectCommand,
} from "../models/project-command.model.js";
import {
assertProjectDeviceRowSyncProjectCommand,
projectDeviceRowSyncCommandType,
} from "../models/project-device-row-sync-project-command.model.js";
import type { CircuitDeviceRowProjectCommandStore } from "../ports/circuit-device-row-project-command.store.js";
import type { CircuitDeviceRowMoveProjectCommandStore } from "../ports/circuit-device-row-move-project-command.store.js";
import type { CircuitDeviceRowStructureProjectCommandStore } from "../ports/circuit-device-row-structure-project-command.store.js";
@@ -54,6 +58,7 @@ import type {
ProjectHistoryDirection,
ProjectHistoryStore,
} from "../ports/project-history.store.js";
import type { ProjectDeviceRowSyncProjectCommandStore } from "../ports/project-device-row-sync-project-command.store.js";
import type { ProjectRevisionSource } from "../ports/project-revision.store.js";
interface DispatchProjectCommandInput {
@@ -75,6 +80,7 @@ export class ProjectCommandService implements ProjectCommandExecutor {
private readonly circuitStructureStore: CircuitStructureProjectCommandStore,
private readonly circuitSectionReorderStore: CircuitSectionReorderProjectCommandStore,
private readonly circuitSectionRenumberStore: CircuitSectionRenumberProjectCommandStore,
private readonly projectDeviceRowSyncStore: ProjectDeviceRowSyncProjectCommandStore,
private readonly historyStore: ProjectHistoryStore
) {}
@@ -212,6 +218,13 @@ export class ProjectCommandService implements ProjectCommandExecutor {
command: input.command,
}).revision;
}
case projectDeviceRowSyncCommandType: {
assertProjectDeviceRowSyncProjectCommand(input.command);
return this.projectDeviceRowSyncStore.execute({
...input,
command: input.command,
}).revision;
}
default:
throw new Error(
`Unsupported project command type: ${input.command.type}.`
@@ -7,6 +7,7 @@ import { CircuitSectionReorderProjectCommandRepository } from "../../db/reposito
import { CircuitSectionRenumberProjectCommandRepository } from "../../db/repositories/circuit-section-renumber-project-command.repository.js";
import { CircuitStructureProjectCommandRepository } from "../../db/repositories/circuit-structure-project-command.repository.js";
import { ProjectHistoryRepository } from "../../db/repositories/project-history.repository.js";
import { ProjectDeviceRowSyncProjectCommandRepository } from "../../db/repositories/project-device-row-sync-project-command.repository.js";
import { ProjectCommandService } from "../../domain/services/project-command.service.js";
export const circuitProjectCommandStore = new CircuitProjectCommandRepository(db);
@@ -22,6 +23,8 @@ export const circuitSectionReorderProjectCommandStore =
new CircuitSectionReorderProjectCommandRepository(db);
export const circuitSectionRenumberProjectCommandStore =
new CircuitSectionRenumberProjectCommandRepository(db);
export const projectDeviceRowSyncProjectCommandStore =
new ProjectDeviceRowSyncProjectCommandRepository(db);
export const projectHistoryStore = new ProjectHistoryRepository(db);
export const projectCommandService = new ProjectCommandService(
circuitProjectCommandStore,
@@ -31,5 +34,6 @@ export const projectCommandService = new ProjectCommandService(
circuitStructureProjectCommandStore,
circuitSectionReorderProjectCommandStore,
circuitSectionRenumberProjectCommandStore,
projectDeviceRowSyncProjectCommandStore,
projectHistoryStore
);