Persist project device synchronization
This commit is contained in:
@@ -1,269 +0,0 @@
|
||||
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 { DistributionBoardRepository } from "../src/db/repositories/distribution-board.repository.js";
|
||||
import { ProjectDeviceRowSyncRepository } from "../src/db/repositories/project-device-row-sync.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 { projects } from "../src/db/schema/projects.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: "Test project" }).run();
|
||||
const board = new DistributionBoardRepository(
|
||||
context.db
|
||||
).createWithCircuitListAndDefaultSections("project-1", "UV-01");
|
||||
const [section] = context.db
|
||||
.select()
|
||||
.from(circuitSections)
|
||||
.where(eq(circuitSections.circuitListId, board.id))
|
||||
.limit(1)
|
||||
.all();
|
||||
context.db
|
||||
.insert(circuits)
|
||||
.values({
|
||||
id: "circuit-1",
|
||||
circuitListId: board.id,
|
||||
sectionId: section.id,
|
||||
equipmentIdentifier: "-1F1",
|
||||
displayName: "Beleuchtung",
|
||||
sortOrder: 10,
|
||||
isReserve: 0,
|
||||
})
|
||||
.run();
|
||||
context.db
|
||||
.insert(projectDevices)
|
||||
.values({
|
||||
id: "project-device-1",
|
||||
projectId: "project-1",
|
||||
name: "Luminaire",
|
||||
displayName: "Office lighting",
|
||||
phaseType: "single_phase",
|
||||
quantity: 4,
|
||||
powerPerUnit: 0.04,
|
||||
simultaneityFactor: 0.8,
|
||||
installedPowerPerUnitKw: 0.04,
|
||||
demandFactor: 0.8,
|
||||
})
|
||||
.run();
|
||||
context.db
|
||||
.insert(circuitDeviceRows)
|
||||
.values([
|
||||
{
|
||||
id: "row-1",
|
||||
circuitId: "circuit-1",
|
||||
linkedProjectDeviceId: "project-device-1",
|
||||
sortOrder: 10,
|
||||
name: "Old luminaire",
|
||||
displayName: "Local row 1",
|
||||
quantity: 1,
|
||||
powerPerUnit: 0.03,
|
||||
simultaneityFactor: 1,
|
||||
},
|
||||
{
|
||||
id: "row-2",
|
||||
circuitId: "circuit-1",
|
||||
linkedProjectDeviceId: "project-device-1",
|
||||
sortOrder: 20,
|
||||
name: "Old luminaire",
|
||||
displayName: "Local row 2",
|
||||
quantity: 2,
|
||||
powerPerUnit: 0.03,
|
||||
simultaneityFactor: 1,
|
||||
},
|
||||
])
|
||||
.run();
|
||||
return context;
|
||||
}
|
||||
|
||||
function synchronizedValues(displayName: string) {
|
||||
return {
|
||||
linkedProjectDeviceId: "project-device-1",
|
||||
name: "Luminaire",
|
||||
displayName,
|
||||
phaseType: "single_phase",
|
||||
quantity: 4,
|
||||
powerPerUnit: 0.04,
|
||||
simultaneityFactor: 0.8,
|
||||
cosPhi: 0.95,
|
||||
remark: "DALI",
|
||||
};
|
||||
}
|
||||
|
||||
function listRows(context: DatabaseContext) {
|
||||
return context.db
|
||||
.select()
|
||||
.from(circuitDeviceRows)
|
||||
.all()
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
}
|
||||
|
||||
describe("project-device row sync repository", () => {
|
||||
it("commits synchronized values for all selected linked rows", () => {
|
||||
const context = createTestDatabase();
|
||||
try {
|
||||
const repository = new ProjectDeviceRowSyncRepository(context.db);
|
||||
|
||||
repository.updateLinkedRows("project-device-1", [
|
||||
{ rowId: "row-1", input: synchronizedValues("Synced row 1") },
|
||||
{ rowId: "row-2", input: synchronizedValues("Synced row 2") },
|
||||
]);
|
||||
|
||||
assert.deepEqual(
|
||||
listRows(context).map((row) => [
|
||||
row.displayName,
|
||||
row.quantity,
|
||||
row.powerPerUnit,
|
||||
row.simultaneityFactor,
|
||||
]),
|
||||
[
|
||||
["Synced row 1", 4, 0.04, 0.8],
|
||||
["Synced row 2", 4, 0.04, 0.8],
|
||||
]
|
||||
);
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rolls back earlier synchronized values when a later row update fails", () => {
|
||||
const context = createTestDatabase();
|
||||
try {
|
||||
context.sqlite.exec(`
|
||||
CREATE TRIGGER fail_second_sync_update
|
||||
BEFORE UPDATE ON circuit_device_rows
|
||||
WHEN OLD.id = 'row-2' AND NEW.display_name = 'Synced'
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'forced sync failure');
|
||||
END;
|
||||
`);
|
||||
const repository = new ProjectDeviceRowSyncRepository(context.db);
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
repository.updateLinkedRows("project-device-1", [
|
||||
{ rowId: "row-1", input: synchronizedValues("Synced") },
|
||||
{ rowId: "row-2", input: synchronizedValues("Synced") },
|
||||
]),
|
||||
/forced sync failure/
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
listRows(context).map((row) => [row.displayName, row.quantity]),
|
||||
[
|
||||
["Local row 1", 1],
|
||||
["Local row 2", 2],
|
||||
]
|
||||
);
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("disconnects all selected rows without changing local values", () => {
|
||||
const context = createTestDatabase();
|
||||
try {
|
||||
const repository = new ProjectDeviceRowSyncRepository(context.db);
|
||||
|
||||
repository.disconnectLinkedRows("project-device-1", ["row-1", "row-2"]);
|
||||
|
||||
assert.deepEqual(
|
||||
listRows(context).map((row) => [
|
||||
row.linkedProjectDeviceId,
|
||||
row.displayName,
|
||||
row.quantity,
|
||||
]),
|
||||
[
|
||||
[null, "Local row 1", 1],
|
||||
[null, "Local row 2", 2],
|
||||
]
|
||||
);
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rolls back earlier disconnects when a later row update fails", () => {
|
||||
const context = createTestDatabase();
|
||||
try {
|
||||
context.sqlite.exec(`
|
||||
CREATE TRIGGER fail_second_disconnect
|
||||
BEFORE UPDATE ON circuit_device_rows
|
||||
WHEN OLD.id = 'row-2' AND NEW.linked_project_device_id IS NULL
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'forced disconnect failure');
|
||||
END;
|
||||
`);
|
||||
const repository = new ProjectDeviceRowSyncRepository(context.db);
|
||||
|
||||
assert.throws(
|
||||
() =>
|
||||
repository.disconnectLinkedRows("project-device-1", ["row-1", "row-2"]),
|
||||
/forced disconnect failure/
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
listRows(context).map((row) => row.linkedProjectDeviceId),
|
||||
["project-device-1", "project-device-1"]
|
||||
);
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reconnects all selected disconnected rows", () => {
|
||||
const context = createTestDatabase();
|
||||
try {
|
||||
context.db.update(circuitDeviceRows).set({ linkedProjectDeviceId: null }).run();
|
||||
const repository = new ProjectDeviceRowSyncRepository(context.db);
|
||||
|
||||
repository.reconnectRows("project-device-1", ["row-1", "row-2"]);
|
||||
|
||||
assert.deepEqual(
|
||||
listRows(context).map((row) => row.linkedProjectDeviceId),
|
||||
["project-device-1", "project-device-1"]
|
||||
);
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("rolls back earlier reconnects when a later row update fails", () => {
|
||||
const context = createTestDatabase();
|
||||
try {
|
||||
context.db.update(circuitDeviceRows).set({ linkedProjectDeviceId: null }).run();
|
||||
context.sqlite.exec(`
|
||||
CREATE TRIGGER fail_second_reconnect
|
||||
BEFORE UPDATE ON circuit_device_rows
|
||||
WHEN OLD.id = 'row-2' AND NEW.linked_project_device_id = 'project-device-1'
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'forced reconnect failure');
|
||||
END;
|
||||
`);
|
||||
const repository = new ProjectDeviceRowSyncRepository(context.db);
|
||||
|
||||
assert.throws(
|
||||
() => repository.reconnectRows("project-device-1", ["row-1", "row-2"]),
|
||||
/forced reconnect failure/
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
listRows(context).map((row) => row.linkedProjectDeviceId),
|
||||
[null, null]
|
||||
);
|
||||
} finally {
|
||||
context.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,9 @@ import { describe, it } from "node:test";
|
||||
import {
|
||||
createProjectDeviceCommandSchema,
|
||||
createProjectDeviceSchema,
|
||||
disconnectProjectDeviceRowsSchema,
|
||||
projectDeviceStructureCommandSchema,
|
||||
synchronizeProjectDeviceRowsSchema,
|
||||
updateProjectDeviceCommandSchema,
|
||||
} from "../src/shared/validation/project-device.schemas.js";
|
||||
|
||||
@@ -87,4 +89,29 @@ describe("project device circuit-first schema", () => {
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
it("requires the current revision for synchronization writes", () => {
|
||||
assert.equal(
|
||||
synchronizeProjectDeviceRowsSchema.safeParse({
|
||||
rowIds: ["row-1"],
|
||||
fields: ["quantity"],
|
||||
}).success,
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
synchronizeProjectDeviceRowsSchema.safeParse({
|
||||
rowIds: ["row-1"],
|
||||
fields: ["quantity"],
|
||||
expectedRevision: 7,
|
||||
}).success,
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
disconnectProjectDeviceRowsSchema.safeParse({
|
||||
rowIds: ["row-1"],
|
||||
expectedRevision: 7,
|
||||
}).success,
|
||||
true
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ function projectDevice() {
|
||||
totalPower: 0.192,
|
||||
cosPhi: 0.95,
|
||||
remark: "DALI",
|
||||
voltageV: 230,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,8 +56,6 @@ function linkedRow() {
|
||||
|
||||
function createService() {
|
||||
const rows = [linkedRow()];
|
||||
const updates: Array<Record<string, unknown>> = [];
|
||||
let transactionCalls = 0;
|
||||
const service = new ProjectDeviceSyncService({
|
||||
projectDeviceRepository: {
|
||||
async findById() {
|
||||
@@ -65,99 +64,104 @@ function createService() {
|
||||
},
|
||||
deviceRowRepository: {
|
||||
async listLinkedByProjectDevice() {
|
||||
return rows.filter((row) => row.linkedProjectDeviceId === "pd1") as never;
|
||||
return rows as never;
|
||||
},
|
||||
async listLinkStatesByIds() {
|
||||
return rows.map((row) => ({ id: row.id, linkedProjectDeviceId: row.linkedProjectDeviceId })) as never;
|
||||
},
|
||||
} as never,
|
||||
deviceRowSyncStore: {
|
||||
updateLinkedRows(_projectDeviceId, changes) {
|
||||
transactionCalls += 1;
|
||||
for (const change of changes) {
|
||||
updates.push({ rowId: change.rowId, ...change.input });
|
||||
Object.assign(rows.find((row) => row.id === change.rowId)!, change.input);
|
||||
}
|
||||
},
|
||||
disconnectLinkedRows(_projectDeviceId, rowIds) {
|
||||
transactionCalls += 1;
|
||||
for (const rowId of rowIds) {
|
||||
const row = rows.find((entry) => entry.id === rowId)!;
|
||||
updates.push({ rowId, linkedProjectDeviceId: undefined, displayName: row.displayName, quantity: row.quantity });
|
||||
Object.assign(row, { linkedProjectDeviceId: null });
|
||||
}
|
||||
},
|
||||
reconnectRows(projectDeviceId, rowIds) {
|
||||
transactionCalls += 1;
|
||||
for (const rowId of rowIds) {
|
||||
Object.assign(rows.find((row) => row.id === rowId)!, { linkedProjectDeviceId: projectDeviceId });
|
||||
}
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
});
|
||||
return { service, rows, updates, transactionCalls: () => transactionCalls };
|
||||
return { service, rows };
|
||||
}
|
||||
|
||||
describe("project device synchronization", () => {
|
||||
it("shows field differences and local overrides without changing rows", async () => {
|
||||
const { service, updates } = createService();
|
||||
const { service, rows } = createService();
|
||||
const before = structuredClone(rows);
|
||||
const preview = await service.getPreview("p1", "pd1");
|
||||
|
||||
assert.equal(updates.length, 0);
|
||||
assert.deepEqual(rows, before);
|
||||
assert.equal(preview.rows[0].equipmentIdentifier, "-1F1");
|
||||
assert.equal(preview.rows[0].differences.some((difference) => difference.field === "quantity"), true);
|
||||
assert.equal(
|
||||
preview.rows[0].differences.find((difference) => difference.field === "displayName")?.isOverridden,
|
||||
preview.rows[0].differences.some(
|
||||
(difference) => difference.field === "quantity"
|
||||
),
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
preview.rows[0].differences.find(
|
||||
(difference) => difference.field === "displayName"
|
||||
)?.isOverridden,
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it("synchronizes only explicitly selected fields", async () => {
|
||||
const { service, rows, transactionCalls } = createService();
|
||||
await service.synchronize("p1", "pd1", ["row1"], ["quantity", "powerPerUnit"]);
|
||||
it("creates a deterministic command for selected synchronization fields", async () => {
|
||||
const { service, rows } = createService();
|
||||
const before = structuredClone(rows);
|
||||
const command = await service.createSynchronizeCommand(
|
||||
"p1",
|
||||
"pd1",
|
||||
["row1"],
|
||||
["quantity", "powerPerUnit"]
|
||||
);
|
||||
|
||||
assert.equal(rows[0].quantity, 6);
|
||||
assert.equal(rows[0].powerPerUnit, 0.04);
|
||||
assert.equal(rows[0].displayName, "Local display name");
|
||||
assert.deepEqual(JSON.parse(rows[0].overriddenFields ?? "[]"), ["displayName"]);
|
||||
assert.equal(transactionCalls(), 1);
|
||||
assert.deepEqual(rows, before);
|
||||
assert.equal(command.payload.operation, "synchronize");
|
||||
assert.equal(command.payload.rows[0].expected.quantity, 2);
|
||||
assert.equal(command.payload.rows[0].target.quantity, 6);
|
||||
assert.equal(command.payload.rows[0].target.powerPerUnit, 0.04);
|
||||
assert.equal(
|
||||
command.payload.rows[0].target.displayName,
|
||||
"Local display name"
|
||||
);
|
||||
assert.deepEqual(
|
||||
JSON.parse(command.payload.rows[0].target.overriddenFields ?? "[]"),
|
||||
["displayName"]
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects rows that are not linked to the selected project device", async () => {
|
||||
const { service } = createService();
|
||||
await assert.rejects(
|
||||
() => service.synchronize("p1", "pd1", ["other-row"], ["quantity"]),
|
||||
() =>
|
||||
service.createSynchronizeCommand(
|
||||
"p1",
|
||||
"pd1",
|
||||
["other-row"],
|
||||
["quantity"]
|
||||
),
|
||||
/not linked/
|
||||
);
|
||||
});
|
||||
|
||||
it("disconnects selected rows without changing local values", async () => {
|
||||
const { service, updates } = createService();
|
||||
await service.disconnect("p1", "pd1", ["row1"]);
|
||||
it("creates a link-only disconnect command", async () => {
|
||||
const { service } = createService();
|
||||
const command = await service.createDisconnectCommand(
|
||||
"p1",
|
||||
"pd1",
|
||||
["row1"]
|
||||
);
|
||||
|
||||
assert.equal(updates[0].linkedProjectDeviceId, undefined);
|
||||
assert.equal(updates[0].displayName, "Local display name");
|
||||
assert.equal(updates[0].quantity, 2);
|
||||
const assignment = command.payload.rows[0];
|
||||
assert.equal(command.payload.operation, "disconnect");
|
||||
assert.equal(assignment.expected.linkedProjectDeviceId, "pd1");
|
||||
assert.equal(assignment.target.linkedProjectDeviceId, null);
|
||||
assert.equal(
|
||||
assignment.target.displayName,
|
||||
assignment.expected.displayName
|
||||
);
|
||||
assert.equal(assignment.target.quantity, assignment.expected.quantity);
|
||||
});
|
||||
|
||||
it("restores synchronized values and override markers", async () => {
|
||||
const { service, rows } = createService();
|
||||
const result = await service.synchronize("p1", "pd1", ["row1"], ["quantity", "powerPerUnit"]);
|
||||
|
||||
await service.restore("p1", "pd1", result.undo.rows);
|
||||
|
||||
assert.equal(rows[0].quantity, 2);
|
||||
assert.equal(rows[0].powerPerUnit, 0.03);
|
||||
assert.deepEqual(JSON.parse(rows[0].overriddenFields ?? "[]"), ["displayName", "quantity"]);
|
||||
it("does not create no-op synchronization commands", async () => {
|
||||
const { service } = createService();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
service.createSynchronizeCommand(
|
||||
"p1",
|
||||
"pd1",
|
||||
["row1"],
|
||||
["category"]
|
||||
),
|
||||
/at least one row/
|
||||
);
|
||||
});
|
||||
|
||||
it("reconnects rows only while they remain disconnected", async () => {
|
||||
const { service, rows } = createService();
|
||||
const result = await service.disconnect("p1", "pd1", ["row1"]);
|
||||
|
||||
await service.reconnect("p1", "pd1", result.undo.rowIds);
|
||||
|
||||
assert.equal(rows[0].linkedProjectDeviceId, "pd1");
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user