482 lines
15 KiB
TypeScript
482 lines
15 KiB
TypeScript
import crypto from "node:crypto";
|
|
import path from "node:path";
|
|
import assert from "node:assert/strict";
|
|
import { describe, it } from "node:test";
|
|
import { eq } from "drizzle-orm";
|
|
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
|
|
import {
|
|
createDatabaseContext,
|
|
type DatabaseContext,
|
|
} from "../src/db/database-context.js";
|
|
import { DistributionBoardFixtureRepository } from "./support/distribution-board-fixture.js";
|
|
import { ProjectSnapshotRepository } from "../src/db/repositories/project-snapshot.repository.js";
|
|
import { ProjectTransferRepository } from "../src/db/repositories/project-transfer.repository.js";
|
|
import { readProjectStateSnapshot } from "../src/db/repositories/project-state-snapshot.persistence.js";
|
|
import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js";
|
|
import { circuitLists } from "../src/db/schema/circuit-lists.js";
|
|
import { circuitSections } from "../src/db/schema/circuit-sections.js";
|
|
import { circuits } from "../src/db/schema/circuits.js";
|
|
import { distributionBoards } from "../src/db/schema/distribution-boards.js";
|
|
import { floors } from "../src/db/schema/floors.js";
|
|
import { projectDevices } from "../src/db/schema/project-devices.js";
|
|
import { projectSnapshots } from "../src/db/schema/project-snapshots.js";
|
|
import { projects } from "../src/db/schema/projects.js";
|
|
import { rooms } from "../src/db/schema/rooms.js";
|
|
import { deserializeProjectStateSnapshot } from "../src/domain/models/project-state-snapshot.model.js";
|
|
import { projectStateSnapshotSchemaVersion } from "../src/domain/models/project-state-snapshot.model.js";
|
|
import { ProjectRevisionConflictError } from "../src/domain/errors/project-revision-conflict.error.js";
|
|
import { ProjectSnapshotNameConflictError } from "../src/domain/errors/project-snapshot-name-conflict.error.js";
|
|
|
|
function createTestDatabase(): DatabaseContext {
|
|
const context = createDatabaseContext(":memory:");
|
|
migrate(context.db, {
|
|
migrationsFolder: path.resolve("src", "db", "migrations"),
|
|
});
|
|
context.db
|
|
.insert(projects)
|
|
.values({
|
|
id: "project-1",
|
|
name: "Snapshot-Projekt",
|
|
singlePhaseVoltageV: 230,
|
|
threePhaseVoltageV: 400,
|
|
})
|
|
.run();
|
|
const board = new DistributionBoardFixtureRepository(
|
|
context.db
|
|
).createWithCircuitListAndDefaultSections("project-1", "UV-01");
|
|
const list = context.db
|
|
.select()
|
|
.from(circuitLists)
|
|
.where(eq(circuitLists.distributionBoardId, board.id))
|
|
.get();
|
|
assert.ok(list);
|
|
const section = context.db
|
|
.select()
|
|
.from(circuitSections)
|
|
.where(eq(circuitSections.circuitListId, list.id))
|
|
.get();
|
|
assert.ok(section);
|
|
context.db
|
|
.insert(floors)
|
|
.values({
|
|
id: "floor-1",
|
|
projectId: "project-1",
|
|
name: "EG",
|
|
sortOrder: 10,
|
|
})
|
|
.run();
|
|
context.db
|
|
.update(distributionBoards)
|
|
.set({ floorId: "floor-1", supplyType: "SV" })
|
|
.where(eq(distributionBoards.id, board.id))
|
|
.run();
|
|
context.db
|
|
.insert(rooms)
|
|
.values({
|
|
id: "room-1",
|
|
projectId: "project-1",
|
|
floorId: "floor-1",
|
|
roomNumber: "001",
|
|
roomName: "Technik",
|
|
})
|
|
.run();
|
|
context.db
|
|
.insert(projectDevices)
|
|
.values({
|
|
id: "device-1",
|
|
projectId: "project-1",
|
|
name: "Pumpe",
|
|
displayName: "Pumpe",
|
|
phaseType: "three_phase",
|
|
quantity: 1,
|
|
powerPerUnit: 2.5,
|
|
simultaneityFactor: 0.8,
|
|
cosPhi: 0.9,
|
|
voltageV: 400,
|
|
})
|
|
.run();
|
|
context.db
|
|
.insert(circuits)
|
|
.values({
|
|
id: "circuit-1",
|
|
circuitListId: list.id,
|
|
sectionId: section.id,
|
|
equipmentIdentifier: "-1F1",
|
|
displayName: "Technik",
|
|
sortOrder: 10,
|
|
voltage: 230,
|
|
isReserve: 0,
|
|
})
|
|
.run();
|
|
context.db
|
|
.insert(circuitDeviceRows)
|
|
.values({
|
|
id: "row-1",
|
|
circuitId: "circuit-1",
|
|
linkedProjectDeviceId: "device-1",
|
|
roomId: "room-1",
|
|
sortOrder: 10,
|
|
name: "Pumpe",
|
|
displayName: "Pumpe lokal",
|
|
phaseType: "three_phase",
|
|
quantity: 1,
|
|
powerPerUnit: 2.5,
|
|
simultaneityFactor: 0.8,
|
|
cosPhi: 0.9,
|
|
})
|
|
.run();
|
|
return context;
|
|
}
|
|
|
|
describe("project snapshot repository", () => {
|
|
it("captures, hashes and lists a complete named logical snapshot", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectSnapshotRepository(context.db);
|
|
const created = repository.createNamed({
|
|
projectId: "project-1",
|
|
expectedRevision: 0,
|
|
name: " Vor Ausschreibung ",
|
|
description: " Sicherer Stand ",
|
|
actorId: "planner-1",
|
|
});
|
|
assert.ok(created);
|
|
assert.equal(created.sourceRevision, 0);
|
|
assert.equal(created.schemaVersion, projectStateSnapshotSchemaVersion);
|
|
assert.equal(created.name, "Vor Ausschreibung");
|
|
assert.equal(created.description, "Sicherer Stand");
|
|
assert.equal(created.createdByActorId, "planner-1");
|
|
assert.match(created.payloadSha256, /^[a-f0-9]{64}$/);
|
|
assert.equal(
|
|
context.db
|
|
.select({ currentRevision: projects.currentRevision })
|
|
.from(projects)
|
|
.where(eq(projects.id, "project-1"))
|
|
.get()?.currentRevision,
|
|
0
|
|
);
|
|
|
|
const persisted = context.db
|
|
.select()
|
|
.from(projectSnapshots)
|
|
.where(eq(projectSnapshots.id, created.id))
|
|
.get();
|
|
assert.ok(persisted);
|
|
assert.equal(
|
|
crypto
|
|
.createHash("sha256")
|
|
.update(persisted.payloadJson)
|
|
.digest("hex"),
|
|
persisted.payloadSha256
|
|
);
|
|
const state = deserializeProjectStateSnapshot(
|
|
persisted.payloadJson
|
|
);
|
|
assert.equal(state.project.id, "project-1");
|
|
assert.equal(state.distributionBoards.length, 1);
|
|
assert.equal(state.distributionBoards[0].floorId, "floor-1");
|
|
assert.equal(state.distributionBoards[0].supplyType, "SV");
|
|
assert.equal(state.circuitLists.length, 1);
|
|
assert.equal(
|
|
state.circuitSections.length,
|
|
context.db.select().from(circuitSections).all().length
|
|
);
|
|
assert.equal(state.circuits.length, 1);
|
|
assert.equal(state.circuits[0].deviceRows.length, 1);
|
|
assert.equal(
|
|
state.circuits[0].deviceRows[0].linkedProjectDeviceId,
|
|
"device-1"
|
|
);
|
|
assert.equal(state.projectDevices.length, 1);
|
|
assert.equal(state.floors.length, 1);
|
|
assert.equal(state.rooms.length, 1);
|
|
assert.deepEqual(repository.listByProject("project-1"), [
|
|
created,
|
|
]);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
|
|
it("rejects stale revisions and duplicate names without partial rows", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectSnapshotRepository(context.db);
|
|
assert.throws(
|
|
() =>
|
|
repository.createNamed({
|
|
projectId: "project-1",
|
|
expectedRevision: 1,
|
|
name: "Stale",
|
|
}),
|
|
ProjectRevisionConflictError
|
|
);
|
|
const created = repository.createNamed({
|
|
projectId: "project-1",
|
|
expectedRevision: 0,
|
|
name: "Freigabe",
|
|
});
|
|
assert.ok(created);
|
|
assert.throws(
|
|
() =>
|
|
repository.createNamed({
|
|
projectId: "project-1",
|
|
expectedRevision: 0,
|
|
name: " Freigabe ",
|
|
}),
|
|
ProjectSnapshotNameConflictError
|
|
);
|
|
assert.equal(
|
|
context.db.select().from(projectSnapshots).all().length,
|
|
1
|
|
);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
|
|
it("distinguishes unknown projects from empty snapshot lists", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectSnapshotRepository(context.db);
|
|
assert.deepEqual(repository.listByProject("project-1"), []);
|
|
assert.equal(repository.listByProject("missing"), null);
|
|
assert.equal(
|
|
repository.createNamed({
|
|
projectId: "missing",
|
|
expectedRevision: 0,
|
|
name: "Unbekannt",
|
|
}),
|
|
null
|
|
);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
|
|
it("verifies stored payload integrity before preparing a restore", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectSnapshotRepository(context.db);
|
|
const snapshot = repository.createNamed({
|
|
projectId: "project-1",
|
|
expectedRevision: 0,
|
|
name: "Freigabe",
|
|
});
|
|
assert.ok(snapshot);
|
|
const prepared = repository.prepareRestore(
|
|
"project-1",
|
|
snapshot.id
|
|
);
|
|
assert.ok(prepared);
|
|
assert.equal(
|
|
prepared.command.payload.targetState.project.id,
|
|
"project-1"
|
|
);
|
|
const currentPayload = JSON.parse(
|
|
context.db
|
|
.select({ payloadJson: projectSnapshots.payloadJson })
|
|
.from(projectSnapshots)
|
|
.where(eq(projectSnapshots.id, snapshot.id))
|
|
.get()!.payloadJson
|
|
) as Record<string, unknown> & {
|
|
project: Record<string, unknown>;
|
|
};
|
|
currentPayload.schemaVersion = 1;
|
|
delete currentPayload.project.internalProjectNumber;
|
|
delete currentPayload.project.externalProjectNumber;
|
|
delete currentPayload.project.buildingOwner;
|
|
delete currentPayload.project.description;
|
|
delete currentPayload.project.enabledDistributionBoardSupplyTypes;
|
|
for (const board of currentPayload.distributionBoards as Array<
|
|
Record<string, unknown>
|
|
>) {
|
|
delete board.floorId;
|
|
delete board.supplyType;
|
|
}
|
|
const legacyPayloadJson = JSON.stringify(currentPayload);
|
|
context.db
|
|
.update(projectSnapshots)
|
|
.set({
|
|
schemaVersion: 1,
|
|
payloadJson: legacyPayloadJson,
|
|
payloadSha256: crypto
|
|
.createHash("sha256")
|
|
.update(legacyPayloadJson)
|
|
.digest("hex"),
|
|
})
|
|
.where(eq(projectSnapshots.id, snapshot.id))
|
|
.run();
|
|
const legacyPrepared = repository.prepareRestore(
|
|
"project-1",
|
|
snapshot.id
|
|
);
|
|
assert.ok(legacyPrepared);
|
|
assert.equal(
|
|
legacyPrepared.command.payload.targetState.project.buildingOwner,
|
|
null
|
|
);
|
|
context.db
|
|
.update(projectSnapshots)
|
|
.set({ payloadJson: `${JSON.stringify({})}\n` })
|
|
.where(eq(projectSnapshots.id, snapshot.id))
|
|
.run();
|
|
assert.throws(
|
|
() => repository.prepareRestore("project-1", snapshot.id),
|
|
/checksum verification failed/
|
|
);
|
|
assert.equal(
|
|
repository.prepareRestore("project-1", "missing"),
|
|
null
|
|
);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("portable project transfer", () => {
|
|
it("exports and atomically duplicates a complete project with new ids", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectTransferRepository(context.db);
|
|
const transfer = repository.exportProject("project-1");
|
|
assert.ok(transfer);
|
|
const duplicate = repository.importDuplicate(transfer);
|
|
assert.notEqual(duplicate.projectId, "project-1");
|
|
assert.equal(duplicate.name, "Snapshot-Projekt (Kopie)");
|
|
|
|
const source = readProjectStateSnapshot(context.db, "project-1");
|
|
const copied = readProjectStateSnapshot(
|
|
context.db,
|
|
duplicate.projectId
|
|
);
|
|
assert.ok(source);
|
|
assert.ok(copied);
|
|
assert.equal(copied.currentRevision, 0);
|
|
assert.equal(copied.state.circuits.length, source.state.circuits.length);
|
|
assert.notEqual(
|
|
copied.state.circuits[0].id,
|
|
source.state.circuits[0].id
|
|
);
|
|
assert.equal(
|
|
copied.state.circuits[0].deviceRows[0].linkedProjectDeviceId,
|
|
copied.state.projectDevices[0].id
|
|
);
|
|
assert.equal(
|
|
copied.state.circuits[0].deviceRows[0].roomId,
|
|
copied.state.rooms[0].id
|
|
);
|
|
assert.equal(
|
|
copied.state.distributionBoards[0].floorId,
|
|
copied.state.floors[0].id
|
|
);
|
|
assert.equal(
|
|
copied.state.distributionBoards[0].supplyType,
|
|
"SV"
|
|
);
|
|
assert.equal(
|
|
copied.state.circuits[0].deviceRows[0].legacyConsumerId,
|
|
null
|
|
);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
|
|
it("prepares same-project replacement and rejects damaged payloads", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectTransferRepository(context.db);
|
|
const transfer = repository.exportProject("project-1");
|
|
assert.ok(transfer);
|
|
const prepared = repository.prepareReplace("project-1", transfer);
|
|
assert.ok(prepared);
|
|
assert.equal(
|
|
prepared.command.payload.targetState.project.id,
|
|
"project-1"
|
|
);
|
|
assert.throws(
|
|
() =>
|
|
repository.importDuplicate({
|
|
...transfer,
|
|
payloadSha256: "0".repeat(64),
|
|
}),
|
|
/checksum verification failed/
|
|
);
|
|
assert.equal(
|
|
context.db.select().from(projects).all().length,
|
|
1
|
|
);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
|
|
it("imports a checksum-valid version-two project transfer", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectTransferRepository(context.db);
|
|
const current = repository.exportProject("project-1");
|
|
assert.ok(current);
|
|
const legacyState = structuredClone(
|
|
current.projectState
|
|
) as unknown as Record<string, unknown> & {
|
|
distributionBoards: Array<Record<string, unknown>>;
|
|
};
|
|
legacyState.schemaVersion = 2;
|
|
delete (
|
|
legacyState.project as Record<string, unknown>
|
|
).enabledDistributionBoardSupplyTypes;
|
|
for (const board of legacyState.distributionBoards) {
|
|
delete board.floorId;
|
|
delete board.supplyType;
|
|
}
|
|
const legacyPayloadJson = JSON.stringify(legacyState);
|
|
const duplicate = repository.importDuplicate({
|
|
...current,
|
|
projectState: legacyState,
|
|
payloadSha256: crypto
|
|
.createHash("sha256")
|
|
.update(legacyPayloadJson)
|
|
.digest("hex"),
|
|
});
|
|
const copied = readProjectStateSnapshot(
|
|
context.db,
|
|
duplicate.projectId
|
|
);
|
|
assert.ok(copied);
|
|
assert.equal(copied.state.distributionBoards[0].floorId, null);
|
|
assert.equal(copied.state.distributionBoards[0].supplyType, null);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
|
|
it("rolls back a duplicate when a late project-state insert fails", () => {
|
|
const context = createTestDatabase();
|
|
try {
|
|
const repository = new ProjectTransferRepository(context.db);
|
|
const transfer = repository.exportProject("project-1");
|
|
assert.ok(transfer);
|
|
context.sqlite.exec(`
|
|
CREATE TRIGGER fail_imported_device_row
|
|
BEFORE INSERT ON circuit_device_rows
|
|
BEGIN
|
|
SELECT RAISE(ABORT, 'forced project transfer failure');
|
|
END;
|
|
`);
|
|
assert.throws(
|
|
() => repository.importDuplicate(transfer),
|
|
/forced project transfer failure/
|
|
);
|
|
assert.equal(
|
|
context.db.select().from(projects).all().length,
|
|
1
|
|
);
|
|
} finally {
|
|
context.close();
|
|
}
|
|
});
|
|
});
|