Persist project device synchronization
This commit is contained in:
@@ -20,9 +20,8 @@ import {
|
||||
listProjectDevices,
|
||||
listProjects,
|
||||
listRooms,
|
||||
reconnectProjectDeviceRows,
|
||||
restoreProjectDeviceRows,
|
||||
synchronizeProjectDeviceRows,
|
||||
undoProjectCommand,
|
||||
updateProjectDevice,
|
||||
updateProjectSettings,
|
||||
} from "../../../frontend/utils/api";
|
||||
@@ -34,7 +33,6 @@ import type {
|
||||
GlobalDeviceDto,
|
||||
ProjectDeviceDto,
|
||||
ProjectDeviceSyncPreviewDto,
|
||||
ProjectDeviceSyncRestoreRowDto,
|
||||
ProjectDto,
|
||||
RoomDto,
|
||||
} from "../../../frontend/types";
|
||||
@@ -57,9 +55,10 @@ const projectDeviceSyncFieldLabels: Record<ProjectDeviceSyncField, string> = {
|
||||
remark: "Bemerkung",
|
||||
};
|
||||
|
||||
type ProjectDeviceUndoState =
|
||||
| { kind: "synchronize"; projectDeviceId: string; rows: ProjectDeviceSyncRestoreRowDto[] }
|
||||
| { kind: "disconnect"; projectDeviceId: string; rowIds: string[] };
|
||||
type ProjectDeviceUndoState = {
|
||||
projectDeviceId: string;
|
||||
revisionNumber: number;
|
||||
};
|
||||
|
||||
const emptyProjectDevice: CreateProjectDeviceInput = {
|
||||
name: "",
|
||||
@@ -180,6 +179,7 @@ export default function ProjectDetailPage() {
|
||||
setProject((current) =>
|
||||
current ? { ...current, currentRevision } : current
|
||||
);
|
||||
setProjectDeviceUndo(null);
|
||||
}
|
||||
|
||||
async function handleCreateBoard(event: FormEvent<HTMLFormElement>) {
|
||||
@@ -409,7 +409,13 @@ export default function ProjectDetailPage() {
|
||||
}
|
||||
|
||||
async function handleSynchronizeProjectDeviceRows() {
|
||||
if (!projectId || !syncPreview || selectedSyncRowIds.length === 0 || selectedSyncFields.length === 0) {
|
||||
if (
|
||||
!projectId ||
|
||||
!project ||
|
||||
!syncPreview ||
|
||||
selectedSyncRowIds.length === 0 ||
|
||||
selectedSyncFields.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
@@ -419,16 +425,17 @@ export default function ProjectDetailPage() {
|
||||
projectId,
|
||||
syncPreview.projectDevice.id,
|
||||
selectedSyncRowIds,
|
||||
selectedSyncFields
|
||||
selectedSyncFields,
|
||||
project.currentRevision
|
||||
);
|
||||
setSyncPreview(result.preview);
|
||||
applyProjectRevision(result.history.currentRevision);
|
||||
setSelectedSyncRowIds(
|
||||
result.preview.rows.filter((row) => row.differences.length > 0).map((row) => row.rowId)
|
||||
);
|
||||
setProjectDeviceUndo({
|
||||
kind: "synchronize",
|
||||
projectDeviceId: syncPreview.projectDevice.id,
|
||||
rows: result.undo.rows,
|
||||
revisionNumber: result.revision.revisionNumber,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Gerätezeilen konnten nicht synchronisiert werden.");
|
||||
@@ -438,7 +445,12 @@ export default function ProjectDetailPage() {
|
||||
}
|
||||
|
||||
async function handleDisconnectProjectDeviceRows() {
|
||||
if (!projectId || !syncPreview || selectedSyncRowIds.length === 0) {
|
||||
if (
|
||||
!projectId ||
|
||||
!project ||
|
||||
!syncPreview ||
|
||||
selectedSyncRowIds.length === 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
@@ -447,13 +459,19 @@ export default function ProjectDetailPage() {
|
||||
const result = await disconnectProjectDeviceRows(
|
||||
projectId,
|
||||
syncPreview.projectDevice.id,
|
||||
selectedSyncRowIds
|
||||
selectedSyncRowIds,
|
||||
project.currentRevision
|
||||
);
|
||||
await openProjectDeviceSyncPreview(syncPreview.projectDevice.id);
|
||||
setSyncPreview(result.preview);
|
||||
setSelectedSyncRowIds(
|
||||
result.preview.rows
|
||||
.filter((row) => row.differences.length > 0)
|
||||
.map((row) => row.rowId)
|
||||
);
|
||||
applyProjectRevision(result.history.currentRevision);
|
||||
setProjectDeviceUndo({
|
||||
kind: "disconnect",
|
||||
projectDeviceId: syncPreview.projectDevice.id,
|
||||
rowIds: result.undo.rowIds,
|
||||
revisionNumber: result.revision.revisionNumber,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Verknüpfungen konnten nicht getrennt werden.");
|
||||
@@ -463,24 +481,29 @@ export default function ProjectDetailPage() {
|
||||
}
|
||||
|
||||
async function handleUndoProjectDeviceOperation() {
|
||||
if (!projectId || !projectDeviceUndo) {
|
||||
if (!projectId || !project || !projectDeviceUndo) {
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const preview =
|
||||
projectDeviceUndo.kind === "synchronize"
|
||||
? await restoreProjectDeviceRows(
|
||||
projectId,
|
||||
projectDeviceUndo.projectDeviceId,
|
||||
projectDeviceUndo.rows
|
||||
)
|
||||
: await reconnectProjectDeviceRows(
|
||||
projectId,
|
||||
projectDeviceUndo.projectDeviceId,
|
||||
projectDeviceUndo.rowIds
|
||||
);
|
||||
if (
|
||||
project.currentRevision !==
|
||||
projectDeviceUndo.revisionNumber
|
||||
) {
|
||||
throw new Error(
|
||||
"Eine neuere Projektänderung verhindert dieses Rückgängig."
|
||||
);
|
||||
}
|
||||
const result = await undoProjectCommand(
|
||||
projectId,
|
||||
project.currentRevision
|
||||
);
|
||||
const preview = await getProjectDeviceSyncPreview(
|
||||
projectId,
|
||||
projectDeviceUndo.projectDeviceId
|
||||
);
|
||||
applyProjectRevision(result.history.currentRevision);
|
||||
setSyncPreview(preview);
|
||||
setSelectedSyncRowIds(preview.rows.filter((row) => row.differences.length > 0).map((row) => row.rowId));
|
||||
setProjectDeviceUndo(null);
|
||||
|
||||
@@ -86,21 +86,6 @@ export class CircuitDeviceRowRepository {
|
||||
.orderBy(asc(distributionBoards.name), asc(circuits.equipmentIdentifier), asc(circuitDeviceRows.sortOrder));
|
||||
}
|
||||
|
||||
async listLinkStatesByIds(projectId: string, rowIds: string[]) {
|
||||
if (rowIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return db
|
||||
.select({
|
||||
id: circuitDeviceRows.id,
|
||||
linkedProjectDeviceId: circuitDeviceRows.linkedProjectDeviceId,
|
||||
})
|
||||
.from(circuitDeviceRows)
|
||||
.innerJoin(circuits, eq(circuitDeviceRows.circuitId, circuits.id))
|
||||
.innerJoin(circuitLists, eq(circuits.circuitListId, circuitLists.id))
|
||||
.where(and(eq(circuitLists.projectId, projectId), inArray(circuitDeviceRows.id, rowIds)));
|
||||
}
|
||||
|
||||
async create(input: CircuitDeviceRowCreateInput) {
|
||||
const id = crypto.randomUUID();
|
||||
await db.insert(circuitDeviceRows).values(toCircuitDeviceRowCreateValues(id, input));
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import type {
|
||||
ProjectDeviceLinkedRowValues,
|
||||
ProjectDeviceRowSyncStore,
|
||||
} from "../../domain/ports/project-device-row-sync.store.js";
|
||||
import type { AppDatabase } from "../database-context.js";
|
||||
import { circuitDeviceRows } from "../schema/circuit-device-rows.js";
|
||||
import { toCircuitDeviceRowUpdateValues } from "./circuit-device-row.persistence.js";
|
||||
|
||||
export class ProjectDeviceRowSyncRepository implements ProjectDeviceRowSyncStore {
|
||||
constructor(private readonly database: AppDatabase) {}
|
||||
|
||||
updateLinkedRows(
|
||||
projectDeviceId: string,
|
||||
changes: Array<{ rowId: string; input: ProjectDeviceLinkedRowValues }>
|
||||
) {
|
||||
this.database.transaction((tx) => {
|
||||
for (const change of changes) {
|
||||
const result = tx
|
||||
.update(circuitDeviceRows)
|
||||
.set(toCircuitDeviceRowUpdateValues(change.input))
|
||||
.where(
|
||||
and(
|
||||
eq(circuitDeviceRows.id, change.rowId),
|
||||
eq(circuitDeviceRows.linkedProjectDeviceId, projectDeviceId)
|
||||
)
|
||||
)
|
||||
.run();
|
||||
if (result.changes !== 1) {
|
||||
throw new Error(
|
||||
"A linked row changed before the operation could be completed."
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
disconnectLinkedRows(projectDeviceId: string, rowIds: string[]) {
|
||||
this.database.transaction((tx) => {
|
||||
for (const rowId of rowIds) {
|
||||
const result = tx
|
||||
.update(circuitDeviceRows)
|
||||
.set({ linkedProjectDeviceId: null })
|
||||
.where(
|
||||
and(
|
||||
eq(circuitDeviceRows.id, rowId),
|
||||
eq(circuitDeviceRows.linkedProjectDeviceId, projectDeviceId)
|
||||
)
|
||||
)
|
||||
.run();
|
||||
if (result.changes !== 1) {
|
||||
throw new Error(
|
||||
"A linked row changed before the operation could be completed."
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
reconnectRows(projectDeviceId: string, rowIds: string[]) {
|
||||
this.database.transaction((tx) => {
|
||||
for (const rowId of rowIds) {
|
||||
const result = tx
|
||||
.update(circuitDeviceRows)
|
||||
.set({ linkedProjectDeviceId: projectDeviceId })
|
||||
.where(
|
||||
and(
|
||||
eq(circuitDeviceRows.id, rowId),
|
||||
isNull(circuitDeviceRows.linkedProjectDeviceId)
|
||||
)
|
||||
)
|
||||
.run();
|
||||
if (result.changes !== 1) {
|
||||
throw new Error(
|
||||
"A disconnected row changed before the operation could be undone."
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
export interface ProjectDeviceLinkedRowValues {
|
||||
linkedProjectDeviceId?: string;
|
||||
name: string;
|
||||
displayName: string;
|
||||
phaseType?: string;
|
||||
connectionKind?: string;
|
||||
costGroup?: string;
|
||||
category?: string;
|
||||
level?: string;
|
||||
roomId?: string;
|
||||
roomNumberSnapshot?: string;
|
||||
roomNameSnapshot?: string;
|
||||
quantity: number;
|
||||
powerPerUnit: number;
|
||||
simultaneityFactor: number;
|
||||
cosPhi?: number;
|
||||
remark?: string;
|
||||
overriddenFields?: string;
|
||||
}
|
||||
|
||||
export interface ProjectDeviceRowSyncStore {
|
||||
updateLinkedRows(
|
||||
projectDeviceId: string,
|
||||
changes: Array<{ rowId: string; input: ProjectDeviceLinkedRowValues }>
|
||||
): void;
|
||||
disconnectLinkedRows(projectDeviceId: string, rowIds: string[]): void;
|
||||
reconnectRows(projectDeviceId: string, rowIds: string[]): void;
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { CircuitDeviceRowRepository } from "../../db/repositories/circuit-device-row.repository.js";
|
||||
import { ProjectDeviceRepository } from "../../db/repositories/project-device.repository.js";
|
||||
import type { ProjectDeviceRowSyncStore } from "../ports/project-device-row-sync.store.js";
|
||||
import {
|
||||
createProjectDeviceRowSyncProjectCommand,
|
||||
projectDeviceSyncRowSnapshotFields,
|
||||
type ProjectDeviceRowSyncProjectCommand,
|
||||
type ProjectDeviceSyncRowSnapshot,
|
||||
} from "../models/project-device-row-sync-project-command.model.js";
|
||||
import {
|
||||
projectDeviceSyncFields,
|
||||
type ProjectDeviceSyncField,
|
||||
@@ -20,20 +25,9 @@ type LinkedRow = Awaited<ReturnType<CircuitDeviceRowRepository["listLinkedByProj
|
||||
|
||||
type SyncDependencies = {
|
||||
projectDeviceRepository: Pick<ProjectDeviceRepository, "findById">;
|
||||
deviceRowRepository: Pick<
|
||||
CircuitDeviceRowRepository,
|
||||
| "listLinkedByProjectDevice"
|
||||
| "listLinkStatesByIds"
|
||||
>;
|
||||
deviceRowSyncStore: ProjectDeviceRowSyncStore;
|
||||
deviceRowRepository: Pick<CircuitDeviceRowRepository, "listLinkedByProjectDevice">;
|
||||
};
|
||||
|
||||
export interface ProjectDeviceSyncRestoreRow {
|
||||
rowId: string;
|
||||
values: Partial<Record<ProjectDeviceSyncField, string | number | null>>;
|
||||
overriddenFields: ProjectDeviceSyncField[];
|
||||
}
|
||||
|
||||
function sourceValue(projectDevice: ProjectDevice, field: ProjectDeviceSyncField) {
|
||||
return projectDevice[field];
|
||||
}
|
||||
@@ -56,19 +50,10 @@ function buildDifferences(projectDevice: ProjectDevice, row: LinkedRow) {
|
||||
export class ProjectDeviceSyncService {
|
||||
private readonly projectDeviceRepository: SyncDependencies["projectDeviceRepository"];
|
||||
private readonly deviceRowRepository: SyncDependencies["deviceRowRepository"];
|
||||
private readonly deviceRowSyncStore?: SyncDependencies["deviceRowSyncStore"];
|
||||
|
||||
constructor(deps?: Partial<SyncDependencies>) {
|
||||
this.projectDeviceRepository = deps?.projectDeviceRepository ?? new ProjectDeviceRepository();
|
||||
this.deviceRowRepository = deps?.deviceRowRepository ?? new CircuitDeviceRowRepository();
|
||||
this.deviceRowSyncStore = deps?.deviceRowSyncStore;
|
||||
}
|
||||
|
||||
private getDeviceRowSyncStore() {
|
||||
if (!this.deviceRowSyncStore) {
|
||||
throw new Error("Project-device row synchronization is not configured.");
|
||||
}
|
||||
return this.deviceRowSyncStore;
|
||||
}
|
||||
|
||||
async getPreview(projectId: string, projectDeviceId: string) {
|
||||
@@ -100,12 +85,12 @@ export class ProjectDeviceSyncService {
|
||||
};
|
||||
}
|
||||
|
||||
async synchronize(
|
||||
async createSynchronizeCommand(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
rowIds: string[],
|
||||
fields: ProjectDeviceSyncField[]
|
||||
) {
|
||||
): Promise<ProjectDeviceRowSyncProjectCommand> {
|
||||
const projectDevice = await this.projectDeviceRepository.findById(projectId, projectDeviceId);
|
||||
if (!projectDevice) {
|
||||
throw new Error("Project device not found.");
|
||||
@@ -113,81 +98,60 @@ export class ProjectDeviceSyncService {
|
||||
const linkedRows = await this.deviceRowRepository.listLinkedByProjectDevice(projectId, projectDeviceId);
|
||||
const selectedRows = this.resolveSelectedRows(linkedRows, rowIds);
|
||||
const selectedFields = [...new Set(fields)];
|
||||
const undoRows: ProjectDeviceSyncRestoreRow[] = selectedRows.map((row) => ({
|
||||
rowId: row.id,
|
||||
values: Object.fromEntries(selectedFields.map((field) => [field, row[field] ?? null])),
|
||||
overriddenFields: parseOverriddenFields(row.overriddenFields),
|
||||
}));
|
||||
|
||||
const changes = [];
|
||||
for (const row of selectedRows) {
|
||||
const next = this.copyRow(row);
|
||||
const assignments = selectedRows.flatMap((row) => {
|
||||
const expected = toSyncSnapshot(row);
|
||||
const target = { ...expected };
|
||||
for (const field of selectedFields) {
|
||||
Object.assign(next, { [field]: sourceValue(projectDevice, field) ?? undefined });
|
||||
Object.assign(target, {
|
||||
[field]: sourceValue(projectDevice, field) ?? null,
|
||||
});
|
||||
}
|
||||
const remainingOverrides = parseOverriddenFields(row.overriddenFields).filter(
|
||||
(field) => !selectedFields.includes(field)
|
||||
);
|
||||
next.overriddenFields = serializeOverriddenFields(remainingOverrides);
|
||||
changes.push({ rowId: row.id, input: next });
|
||||
}
|
||||
this.getDeviceRowSyncStore().updateLinkedRows(projectDeviceId, changes);
|
||||
|
||||
return {
|
||||
preview: await this.getPreview(projectId, projectDeviceId),
|
||||
undo: { rows: undoRows },
|
||||
};
|
||||
}
|
||||
|
||||
async disconnect(projectId: string, projectDeviceId: string, rowIds: string[]) {
|
||||
const linkedRows = await this.deviceRowRepository.listLinkedByProjectDevice(projectId, projectDeviceId);
|
||||
const selectedRows = this.resolveSelectedRows(linkedRows, rowIds);
|
||||
const disconnectedRowIds = selectedRows.map((row) => row.id);
|
||||
|
||||
this.getDeviceRowSyncStore().disconnectLinkedRows(
|
||||
projectDeviceId,
|
||||
disconnectedRowIds
|
||||
);
|
||||
|
||||
return { disconnectedRowIds, undo: { rowIds: disconnectedRowIds } };
|
||||
}
|
||||
|
||||
async restore(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
restoreRows: ProjectDeviceSyncRestoreRow[]
|
||||
) {
|
||||
const linkedRows = await this.deviceRowRepository.listLinkedByProjectDevice(projectId, projectDeviceId);
|
||||
const selectedRows = this.resolveSelectedRows(linkedRows, restoreRows.map((row) => row.rowId));
|
||||
const restoreById = new Map(restoreRows.map((row) => [row.rowId, row]));
|
||||
const changes = selectedRows.map((row) => {
|
||||
const restore = restoreById.get(row.id)!;
|
||||
const next = this.copyRow(row);
|
||||
for (const [field, value] of Object.entries(restore.values) as Array<
|
||||
[ProjectDeviceSyncField, string | number | null]
|
||||
>) {
|
||||
Object.assign(next, { [field]: value ?? undefined });
|
||||
}
|
||||
next.overriddenFields = serializeOverriddenFields(restore.overriddenFields);
|
||||
return { rowId: row.id, input: next };
|
||||
target.overriddenFields =
|
||||
serializeOverriddenFields(remainingOverrides) ?? null;
|
||||
return snapshotsEqual(expected, target)
|
||||
? []
|
||||
: [{ rowId: row.id, expected, target }];
|
||||
});
|
||||
|
||||
this.getDeviceRowSyncStore().updateLinkedRows(projectDeviceId, changes);
|
||||
return this.getPreview(projectId, projectDeviceId);
|
||||
return createProjectDeviceRowSyncProjectCommand(
|
||||
projectDeviceId,
|
||||
"synchronize",
|
||||
assignments
|
||||
);
|
||||
}
|
||||
|
||||
async reconnect(projectId: string, projectDeviceId: string, rowIds: string[]) {
|
||||
const projectDevice = await this.projectDeviceRepository.findById(projectId, projectDeviceId);
|
||||
async createDisconnectCommand(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
rowIds: string[]
|
||||
): Promise<ProjectDeviceRowSyncProjectCommand> {
|
||||
const projectDevice = await this.projectDeviceRepository.findById(
|
||||
projectId,
|
||||
projectDeviceId
|
||||
);
|
||||
if (!projectDevice) {
|
||||
throw new Error("Project device not found.");
|
||||
}
|
||||
const uniqueRowIds = [...new Set(rowIds)];
|
||||
const linkStates = await this.deviceRowRepository.listLinkStatesByIds(projectId, uniqueRowIds);
|
||||
if (linkStates.length !== uniqueRowIds.length || linkStates.some((row) => row.linkedProjectDeviceId !== null)) {
|
||||
throw new Error("One or more rows cannot be reconnected.");
|
||||
}
|
||||
this.getDeviceRowSyncStore().reconnectRows(projectDeviceId, uniqueRowIds);
|
||||
return this.getPreview(projectId, projectDeviceId);
|
||||
const linkedRows = await this.deviceRowRepository.listLinkedByProjectDevice(projectId, projectDeviceId);
|
||||
const selectedRows = this.resolveSelectedRows(linkedRows, rowIds);
|
||||
return createProjectDeviceRowSyncProjectCommand(
|
||||
projectDeviceId,
|
||||
"disconnect",
|
||||
selectedRows.map((row) => {
|
||||
const expected = toSyncSnapshot(row);
|
||||
return {
|
||||
rowId: row.id,
|
||||
expected,
|
||||
target: {
|
||||
...expected,
|
||||
linkedProjectDeviceId: null,
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSelectedRows(linkedRows: LinkedRow[], rowIds: string[]) {
|
||||
@@ -200,25 +164,31 @@ export class ProjectDeviceSyncService {
|
||||
return selectedRows;
|
||||
}
|
||||
|
||||
private copyRow(row: LinkedRow) {
|
||||
return {
|
||||
linkedProjectDeviceId: row.linkedProjectDeviceId ?? undefined,
|
||||
name: row.name,
|
||||
displayName: row.displayName,
|
||||
phaseType: row.phaseType ?? undefined,
|
||||
connectionKind: row.connectionKind ?? undefined,
|
||||
costGroup: row.costGroup ?? undefined,
|
||||
category: row.category ?? undefined,
|
||||
level: row.level ?? undefined,
|
||||
roomId: row.roomId ?? undefined,
|
||||
roomNumberSnapshot: row.roomNumberSnapshot ?? undefined,
|
||||
roomNameSnapshot: row.roomNameSnapshot ?? undefined,
|
||||
quantity: row.quantity,
|
||||
powerPerUnit: row.powerPerUnit,
|
||||
simultaneityFactor: row.simultaneityFactor,
|
||||
cosPhi: row.cosPhi ?? undefined,
|
||||
remark: row.remark ?? undefined,
|
||||
overriddenFields: row.overriddenFields ?? undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function toSyncSnapshot(row: LinkedRow): ProjectDeviceSyncRowSnapshot {
|
||||
return {
|
||||
linkedProjectDeviceId: row.linkedProjectDeviceId,
|
||||
name: row.name,
|
||||
displayName: row.displayName,
|
||||
phaseType: row.phaseType,
|
||||
connectionKind: row.connectionKind,
|
||||
costGroup: row.costGroup,
|
||||
category: row.category,
|
||||
quantity: row.quantity,
|
||||
powerPerUnit: row.powerPerUnit,
|
||||
simultaneityFactor: row.simultaneityFactor,
|
||||
cosPhi: row.cosPhi,
|
||||
remark: row.remark,
|
||||
overriddenFields: row.overriddenFields,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshotsEqual(
|
||||
left: ProjectDeviceSyncRowSnapshot,
|
||||
right: ProjectDeviceSyncRowSnapshot
|
||||
) {
|
||||
return projectDeviceSyncRowSnapshotFields.every(
|
||||
(field) => left[field] === right[field]
|
||||
);
|
||||
}
|
||||
|
||||
+2
-17
@@ -165,24 +165,9 @@ export interface ProjectDeviceSyncPreviewDto {
|
||||
rows: ProjectDeviceSyncRowDto[];
|
||||
}
|
||||
|
||||
export interface ProjectDeviceSyncRestoreRowDto {
|
||||
rowId: string;
|
||||
values: Partial<Record<ProjectDeviceSyncField, string | number | null>>;
|
||||
overriddenFields: ProjectDeviceSyncField[];
|
||||
}
|
||||
|
||||
export interface ProjectDeviceSyncResultDto {
|
||||
export interface ProjectDeviceSyncCommandResultDto
|
||||
extends ProjectCommandResultDto {
|
||||
preview: ProjectDeviceSyncPreviewDto;
|
||||
undo: {
|
||||
rows: ProjectDeviceSyncRestoreRowDto[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface ProjectDeviceDisconnectResultDto {
|
||||
disconnectedRowIds: string[];
|
||||
undo: {
|
||||
rowIds: string[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface CircuitTreeDeviceRowDto {
|
||||
|
||||
@@ -12,10 +12,8 @@ import type {
|
||||
ProjectDeviceCommandResultDto,
|
||||
ProjectDeviceDto,
|
||||
ProjectHistoryStateDto,
|
||||
ProjectDeviceDisconnectResultDto,
|
||||
ProjectDeviceSyncCommandResultDto,
|
||||
ProjectDeviceSyncPreviewDto,
|
||||
ProjectDeviceSyncRestoreRowDto,
|
||||
ProjectDeviceSyncResultDto,
|
||||
ProjectDto,
|
||||
RoomDto,
|
||||
CircuitTreeResponseDto,
|
||||
@@ -387,13 +385,14 @@ export function synchronizeProjectDeviceRows(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
rowIds: string[],
|
||||
fields: ProjectDeviceSyncField[]
|
||||
fields: ProjectDeviceSyncField[],
|
||||
expectedRevision: number
|
||||
) {
|
||||
return request<ProjectDeviceSyncResultDto>(
|
||||
return request<ProjectDeviceSyncCommandResultDto>(
|
||||
`/api/project-devices/projects/${projectId}/${projectDeviceId}/synchronize`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ rowIds, fields }),
|
||||
body: JSON.stringify({ rowIds, fields, expectedRevision }),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -401,41 +400,14 @@ export function synchronizeProjectDeviceRows(
|
||||
export function disconnectProjectDeviceRows(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
rowIds: string[]
|
||||
rowIds: string[],
|
||||
expectedRevision: number
|
||||
) {
|
||||
return request<ProjectDeviceDisconnectResultDto>(
|
||||
return request<ProjectDeviceSyncCommandResultDto>(
|
||||
`/api/project-devices/projects/${projectId}/${projectDeviceId}/disconnect`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ rowIds }),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function restoreProjectDeviceRows(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
rows: ProjectDeviceSyncRestoreRowDto[]
|
||||
) {
|
||||
return request<ProjectDeviceSyncPreviewDto>(
|
||||
`/api/project-devices/projects/${projectId}/${projectDeviceId}/restore`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ rows }),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function reconnectProjectDeviceRows(
|
||||
projectId: string,
|
||||
projectDeviceId: string,
|
||||
rowIds: string[]
|
||||
) {
|
||||
return request<ProjectDeviceSyncPreviewDto>(
|
||||
`/api/project-devices/projects/${projectId}/${projectDeviceId}/reconnect`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ rowIds }),
|
||||
body: JSON.stringify({ rowIds, expectedRevision }),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import { db } from "../../db/client.js";
|
||||
import { ProjectDeviceRowSyncRepository } from "../../db/repositories/project-device-row-sync.repository.js";
|
||||
import { ProjectDeviceSyncService } from "../../domain/services/project-device-sync.service.js";
|
||||
|
||||
export const projectDeviceSyncService = new ProjectDeviceSyncService({
|
||||
deviceRowSyncStore: new ProjectDeviceRowSyncRepository(db),
|
||||
});
|
||||
export const projectDeviceSyncService = new ProjectDeviceSyncService();
|
||||
|
||||
@@ -14,8 +14,6 @@ import {
|
||||
createProjectDeviceCommandSchema,
|
||||
disconnectProjectDeviceRowsSchema,
|
||||
projectDeviceStructureCommandSchema,
|
||||
reconnectProjectDeviceRowsSchema,
|
||||
restoreProjectDeviceRowsSchema,
|
||||
synchronizeProjectDeviceRowsSchema,
|
||||
updateProjectDeviceCommandSchema,
|
||||
} from "../../shared/validation/project-device.schemas.js";
|
||||
@@ -218,32 +216,25 @@ export async function synchronizeProjectDeviceRows(req: Request, res: Response)
|
||||
return res.status(400).json({ error: parsed.error.flatten() });
|
||||
}
|
||||
try {
|
||||
const result = await projectDeviceSyncService.synchronize(
|
||||
const command = await projectDeviceSyncService.createSynchronizeCommand(
|
||||
projectId,
|
||||
projectDeviceId,
|
||||
parsed.data.rowIds,
|
||||
parsed.data.fields
|
||||
);
|
||||
return res.json(result);
|
||||
const result = projectCommandService.executeUser({
|
||||
projectId,
|
||||
expectedRevision: parsed.data.expectedRevision,
|
||||
description: "Projektgerät in Stromkreiszeilen synchronisieren",
|
||||
command,
|
||||
});
|
||||
const preview = await projectDeviceSyncService.getPreview(
|
||||
projectId,
|
||||
projectDeviceId
|
||||
);
|
||||
return res.json({ ...result, preview });
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: error instanceof Error ? error.message : "Failed to synchronize rows." });
|
||||
}
|
||||
}
|
||||
|
||||
export async function restoreProjectDeviceRows(req: Request, res: Response) {
|
||||
const { projectId, projectDeviceId } = req.params;
|
||||
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
||||
return res.status(400).json({ error: "Invalid parameters" });
|
||||
}
|
||||
const parsed = restoreProjectDeviceRowsSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
return res.status(400).json({ error: parsed.error.flatten() });
|
||||
}
|
||||
try {
|
||||
const preview = await projectDeviceSyncService.restore(projectId, projectDeviceId, parsed.data.rows);
|
||||
return res.json(preview);
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: error instanceof Error ? error.message : "Failed to restore rows." });
|
||||
return respondWithProjectCommandError(error, res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,26 +248,23 @@ export async function disconnectProjectDeviceRows(req: Request, res: Response) {
|
||||
return res.status(400).json({ error: parsed.error.flatten() });
|
||||
}
|
||||
try {
|
||||
const result = await projectDeviceSyncService.disconnect(projectId, projectDeviceId, parsed.data.rowIds);
|
||||
return res.json(result);
|
||||
const command = await projectDeviceSyncService.createDisconnectCommand(
|
||||
projectId,
|
||||
projectDeviceId,
|
||||
parsed.data.rowIds
|
||||
);
|
||||
const result = projectCommandService.executeUser({
|
||||
projectId,
|
||||
expectedRevision: parsed.data.expectedRevision,
|
||||
description: "Projektgerät-Verknüpfungen trennen",
|
||||
command,
|
||||
});
|
||||
const preview = await projectDeviceSyncService.getPreview(
|
||||
projectId,
|
||||
projectDeviceId
|
||||
);
|
||||
return res.json({ ...result, preview });
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: error instanceof Error ? error.message : "Failed to disconnect rows." });
|
||||
}
|
||||
}
|
||||
|
||||
export async function reconnectProjectDeviceRows(req: Request, res: Response) {
|
||||
const { projectId, projectDeviceId } = req.params;
|
||||
if (typeof projectId !== "string" || typeof projectDeviceId !== "string") {
|
||||
return res.status(400).json({ error: "Invalid parameters" });
|
||||
}
|
||||
const parsed = reconnectProjectDeviceRowsSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
return res.status(400).json({ error: parsed.error.flatten() });
|
||||
}
|
||||
try {
|
||||
const preview = await projectDeviceSyncService.reconnect(projectId, projectDeviceId, parsed.data.rowIds);
|
||||
return res.json(preview);
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: error instanceof Error ? error.message : "Failed to reconnect rows." });
|
||||
return respondWithProjectCommandError(error, res);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ import {
|
||||
disconnectProjectDeviceRows,
|
||||
getProjectDeviceSyncPreview,
|
||||
listProjectDevicesByProject,
|
||||
reconnectProjectDeviceRows,
|
||||
restoreProjectDeviceRows,
|
||||
synchronizeProjectDeviceRows,
|
||||
updateProjectDevice,
|
||||
} from "../controllers/project-device.controller.js";
|
||||
@@ -19,8 +17,6 @@ projectDeviceRouter.post("/projects/:projectId", createProjectDevice);
|
||||
projectDeviceRouter.post("/projects/:projectId/import-global/:globalDeviceId", copyGlobalDeviceToProject);
|
||||
projectDeviceRouter.get("/projects/:projectId/:projectDeviceId/links", getProjectDeviceSyncPreview);
|
||||
projectDeviceRouter.post("/projects/:projectId/:projectDeviceId/synchronize", synchronizeProjectDeviceRows);
|
||||
projectDeviceRouter.post("/projects/:projectId/:projectDeviceId/restore", restoreProjectDeviceRows);
|
||||
projectDeviceRouter.post("/projects/:projectId/:projectDeviceId/disconnect", disconnectProjectDeviceRows);
|
||||
projectDeviceRouter.post("/projects/:projectId/:projectDeviceId/reconnect", reconnectProjectDeviceRows);
|
||||
projectDeviceRouter.put("/projects/:projectId/:projectDeviceId", updateProjectDevice);
|
||||
projectDeviceRouter.delete("/projects/:projectId/:projectDeviceId", deleteProjectDevice);
|
||||
|
||||
@@ -37,39 +37,13 @@ export const projectDeviceStructureCommandSchema = z.object({
|
||||
export const synchronizeProjectDeviceRowsSchema = z.object({
|
||||
rowIds: z.array(z.string().min(1)).min(1),
|
||||
fields: z.array(z.enum(projectDeviceSyncFields)).min(1),
|
||||
expectedRevision: expectedProjectRevisionSchema,
|
||||
});
|
||||
|
||||
export const disconnectProjectDeviceRowsSchema = z.object({
|
||||
rowIds: z.array(z.string().min(1)).min(1),
|
||||
expectedRevision: expectedProjectRevisionSchema,
|
||||
});
|
||||
|
||||
const projectDeviceRestoreValuesSchema = z.object({
|
||||
name: z.string().optional(),
|
||||
displayName: z.string().optional(),
|
||||
phaseType: z.enum(["single_phase", "three_phase"]).optional(),
|
||||
connectionKind: z.string().nullable().optional(),
|
||||
costGroup: z.string().nullable().optional(),
|
||||
category: z.string().nullable().optional(),
|
||||
quantity: z.number().min(0).optional(),
|
||||
powerPerUnit: z.number().min(0).optional(),
|
||||
simultaneityFactor: z.number().min(0).max(1).optional(),
|
||||
cosPhi: z.number().min(0).max(1).nullable().optional(),
|
||||
remark: z.string().nullable().optional(),
|
||||
});
|
||||
|
||||
export const restoreProjectDeviceRowsSchema = z.object({
|
||||
rows: z
|
||||
.array(
|
||||
z.object({
|
||||
rowId: z.string().min(1),
|
||||
values: projectDeviceRestoreValuesSchema,
|
||||
overriddenFields: z.array(z.enum(projectDeviceSyncFields)),
|
||||
})
|
||||
)
|
||||
.min(1),
|
||||
});
|
||||
|
||||
export const reconnectProjectDeviceRowsSchema = disconnectProjectDeviceRowsSchema;
|
||||
|
||||
export type CreateProjectDeviceInput = z.infer<typeof createProjectDeviceSchema>;
|
||||
export type UpdateProjectDeviceInput = z.infer<typeof updateProjectDeviceSchema>;
|
||||
|
||||
Reference in New Issue
Block a user