import path from "node:path"; import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { asc, eq } from "drizzle-orm"; import { migrate } from "drizzle-orm/better-sqlite3/migrator"; import { createDatabaseContext, type DatabaseContext, } from "../src/db/database-context.js"; import { DistributionBoardRepository } from "../src/db/repositories/distribution-board.repository.js"; import { ProjectDeviceStructureProjectCommandRepository } from "../src/db/repositories/project-device-structure-project-command.repository.js"; import { ProjectHistoryRepository } from "../src/db/repositories/project-history.repository.js"; import { circuitDeviceRows } from "../src/db/schema/circuit-device-rows.js"; import { circuitSections } from "../src/db/schema/circuit-sections.js"; import { circuits } from "../src/db/schema/circuits.js"; import { projectDevices } from "../src/db/schema/project-devices.js"; import { projectRevisions } from "../src/db/schema/project-revisions.js"; import { projects } from "../src/db/schema/projects.js"; import { createProjectDeviceDeleteProjectCommand, createProjectDeviceInsertProjectCommand, type ProjectDeviceSnapshot, } from "../src/domain/models/project-device-structure-project-command.model.js"; function newProjectDeviceSnapshot(): ProjectDeviceSnapshot { return { id: "project-device-new", projectId: "project-1", name: "Socket", displayName: "Office socket", phaseType: "single_phase", connectionKind: null, costGroup: "440", category: "socket", quantity: 2, powerPerUnit: 0.2, simultaneityFactor: 0.5, cosPhi: null, remark: null, voltageV: 230, }; } 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: "Test project" }, { id: "project-2", name: "Other project" }, ]) .run(); const boards = new DistributionBoardRepository(context.db); const board = boards.createWithCircuitListAndDefaultSections( "project-1", "UV-01" ); const foreignBoard = boards.createWithCircuitListAndDefaultSections( "project-2", "UV-02" ); const section = context.db .select() .from(circuitSections) .where(eq(circuitSections.circuitListId, board.id)) .get(); const foreignSection = context.db .select() .from(circuitSections) .where(eq(circuitSections.circuitListId, foreignBoard.id)) .get(); assert.ok(section); assert.ok(foreignSection); context.db .insert(projectDevices) .values([ { id: "project-device-1", projectId: "project-1", name: "Luminaire", displayName: "Office lighting", phaseType: "single_phase", connectionKind: "fixed", costGroup: "440", category: "lighting", quantity: 4, powerPerUnit: 0.04, simultaneityFactor: 0.8, cosPhi: 0.95, remark: "DALI", voltageV: 230, }, { id: "project-device-foreign", projectId: "project-2", name: "Foreign device", displayName: "Foreign device", phaseType: "three_phase", quantity: 1, powerPerUnit: 1, simultaneityFactor: 1, }, ]) .run(); context.db .insert(circuits) .values([ { id: "circuit-1", circuitListId: board.id, sectionId: section.id, equipmentIdentifier: "-1F1", sortOrder: 10, }, { id: "circuit-foreign", circuitListId: foreignBoard.id, sectionId: foreignSection.id, equipmentIdentifier: "-1F1", sortOrder: 10, }, ]) .run(); context.db .insert(circuitDeviceRows) .values([ { id: "row-1", circuitId: "circuit-1", linkedProjectDeviceId: "project-device-1", sortOrder: 10, name: "Luminaire", displayName: "Local row 1", phaseType: "single_phase", quantity: 1, powerPerUnit: 0.03, simultaneityFactor: 1, overriddenFields: '["displayName","quantity"]', }, { id: "row-2", circuitId: "circuit-1", linkedProjectDeviceId: "project-device-1", sortOrder: 20, name: "Luminaire", displayName: "Local row 2", phaseType: "single_phase", quantity: 2, powerPerUnit: 0.03, simultaneityFactor: 1, overriddenFields: '["displayName"]', }, ]) .run(); return context; } function getProjectDevice( context: DatabaseContext, id: string ) { return context.db .select() .from(projectDevices) .where(eq(projectDevices.id, id)) .get(); } function getLinkedRowState(context: DatabaseContext) { return context.db .select({ id: circuitDeviceRows.id, linkedProjectDeviceId: circuitDeviceRows.linkedProjectDeviceId, displayName: circuitDeviceRows.displayName, quantity: circuitDeviceRows.quantity, overriddenFields: circuitDeviceRows.overriddenFields, }) .from(circuitDeviceRows) .where(eq(circuitDeviceRows.circuitId, "circuit-1")) .orderBy(asc(circuitDeviceRows.id)) .all(); } describe("project-device structure project-command repository", () => { it("inserts a stable project device and supports undo and redo", () => { const context = createTestDatabase(); try { const store = new ProjectDeviceStructureProjectCommandRepository( context.db ); const command = createProjectDeviceInsertProjectCommand( newProjectDeviceSnapshot() ); const inserted = store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command, }); assert.equal( getProjectDevice(context, "project-device-new") ?.displayName, "Office socket" ); store.execute({ projectId: "project-1", expectedRevision: 1, source: "undo", historyTargetChangeSetId: inserted.revision.changeSetId, command: inserted.inverse, }); assert.equal( getProjectDevice(context, "project-device-new"), undefined ); store.execute({ projectId: "project-1", expectedRevision: 2, source: "redo", historyTargetChangeSetId: inserted.revision.changeSetId, command, }); assert.deepEqual( new ProjectHistoryRepository(context.db).getState( "project-1" ), { projectId: "project-1", currentRevision: 3, undoDepth: 1, redoDepth: 0, undoChangeSetId: inserted.revision.changeSetId, redoChangeSetId: null, } ); } finally { context.close(); } }); it("deletes a device and restores its exact linked rows", () => { const context = createTestDatabase(); try { const store = new ProjectDeviceStructureProjectCommandRepository( context.db ); const beforeRows = getLinkedRowState(context); const command = createProjectDeviceDeleteProjectCommand( "project-device-1", "project-1" ); const deleted = store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command, }); assert.equal( getProjectDevice(context, "project-device-1"), undefined ); assert.deepEqual( getLinkedRowState(context).map( (row) => row.linkedProjectDeviceId ), [null, null] ); store.execute({ projectId: "project-1", expectedRevision: 1, source: "undo", historyTargetChangeSetId: deleted.revision.changeSetId, command: deleted.inverse, }); assert.equal( getProjectDevice(context, "project-device-1") ?.displayName, "Office lighting" ); assert.deepEqual(getLinkedRowState(context), beforeRows); store.execute({ projectId: "project-1", expectedRevision: 2, source: "redo", historyTargetChangeSetId: deleted.revision.changeSetId, command, }); assert.deepEqual( getLinkedRowState(context).map( (row) => row.linkedProjectDeviceId ), [null, null] ); } finally { context.close(); } }); it("rejects unsafe user links, duplicate ids and foreign deletes", () => { const context = createTestDatabase(); try { const store = new ProjectDeviceStructureProjectCommandRepository( context.db ); const disconnectedRow = context.db .select() .from(circuitDeviceRows) .where(eq(circuitDeviceRows.id, "row-1")) .get(); assert.ok(disconnectedRow); assert.throws( () => store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createProjectDeviceInsertProjectCommand( newProjectDeviceSnapshot(), [ { ...disconnectedRow, linkedProjectDeviceId: null, }, ] ), }), /cannot reconnect existing rows/ ); assert.throws( () => store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createProjectDeviceInsertProjectCommand({ ...newProjectDeviceSnapshot(), id: "project-device-1", }), }), /id already exists/ ); assert.throws( () => store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createProjectDeviceDeleteProjectCommand( "project-device-foreign", "project-1" ), }), /does not belong to project/ ); assert.equal( context.db.select().from(projectRevisions).all().length, 0 ); } finally { context.close(); } }); it("refuses undo when a disconnected row changed", () => { const context = createTestDatabase(); try { const store = new ProjectDeviceStructureProjectCommandRepository( context.db ); const deleted = store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createProjectDeviceDeleteProjectCommand( "project-device-1", "project-1" ), }); context.db .update(circuitDeviceRows) .set({ displayName: "Changed while disconnected" }) .where(eq(circuitDeviceRows.id, "row-1")) .run(); assert.throws( () => store.execute({ projectId: "project-1", expectedRevision: 1, source: "undo", historyTargetChangeSetId: deleted.revision.changeSetId, command: deleted.inverse, }), /row changed before insertion/ ); assert.equal( getProjectDevice(context, "project-device-1"), undefined ); assert.deepEqual( getLinkedRowState(context).map( (row) => row.linkedProjectDeviceId ), [null, null] ); assert.equal( context.db.select().from(projectRevisions).all().length, 1 ); } finally { context.close(); } }); it("rolls back deletion, disconnected links and history together", () => { const context = createTestDatabase(); try { context.sqlite.exec(` CREATE TRIGGER fail_project_device_structure_history BEFORE INSERT ON project_history_stack_entries BEGIN SELECT RAISE(ABORT, 'forced project-device structure history failure'); END; `); const store = new ProjectDeviceStructureProjectCommandRepository( context.db ); const beforeRows = getLinkedRowState(context); assert.throws( () => store.execute({ projectId: "project-1", expectedRevision: 0, source: "user", command: createProjectDeviceDeleteProjectCommand( "project-device-1", "project-1" ), }), /forced project-device structure history failure/ ); assert.equal( getProjectDevice(context, "project-device-1") ?.displayName, "Office lighting" ); assert.deepEqual(getLinkedRowState(context), beforeRows); assert.equal( context.db.select().from(projectRevisions).all().length, 0 ); } finally { context.close(); } }); it("rolls back insertion for a stale project revision", () => { const context = createTestDatabase(); try { const store = new ProjectDeviceStructureProjectCommandRepository( context.db ); assert.throws( () => store.execute({ projectId: "project-1", expectedRevision: 1, source: "user", command: createProjectDeviceInsertProjectCommand( newProjectDeviceSnapshot() ), }), /at revision 0, expected 1/ ); assert.equal( getProjectDevice(context, "project-device-new"), undefined ); } finally { context.close(); } }); });