visualisierung

This commit is contained in:
marco committed 2026-10-26 07:34:23 +01:00
1 parent d0655f3638
commit 367c93c93e
84 files changed
+2265 -148

No files matched your search

+296
View File
@@ -0,0 +1,296 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import * as sql from 'mssql';
import { createHash } from 'node:crypto';
import { Anlage } from '../../_schemas/anlage.schema';
import { ProConViewAggregate } from '../../_schemas/anlagen/procon-view-aggregate';
import type { ProConZuordnung } from '../../_schemas/anlagen/procon-zuordnung';
import { SqlService } from '../../infrastructure/sql/sql.service';
import { validateSyncXml } from './sync-xml';
import { DrawService } from '../../draw/draw.service';
import type { GrafikGeneratorDaten } from '../../_schemas/anlagen/procon-view-aggregate';
export interface SyncValues { x: number; y: number; width: number; height: number; show: boolean }
export interface SyncRequest {
version: string;
direction: 'toLocal' | 'toProcon' | 'saveLocal';
values: SyncValues;
viewId?: string;
state?: string;
xaml?: string;
xamlOnly?: boolean;
}
export interface GroupSyncValues extends SyncValues { z: number }
function validateGroupValues(values: GroupSyncValues) {
validateSyncValues(values);
if (!Number.isInteger(values.z)) throw new BadRequestException('Z-Index muss eine ganze Zahl sein');
}
export interface GroupSyncRequest {
version: string;
direction: 'toLocal' | 'toProcon' | 'saveLocal';
masterId: string;
elementIds?: string[];
elements?: { id: string; values: GroupSyncValues; generator?: GrafikGeneratorDaten }[];
}
export function validateSyncValues(values: SyncValues) {
if (!values || ['x', 'y', 'width', 'height'].some(key => typeof values[key] !== 'number' || !Number.isFinite(values[key])) ||
values.width < 0 || values.height < 0 || typeof values.show !== 'boolean')
throw new BadRequestException('Position und Maße müssen gültige Zahlen sein; Sichtbarkeit muss Boolean sein');
}
export function decodeXaml(value: string | null | undefined) {
if (!value) return '';
if (value.trimStart().startsWith('<')) return value;
return Buffer.from(value, 'base64').toString('utf8');
}
@Injectable()
export class ProConSyncService {
constructor(
@InjectModel(Anlage.name) private readonly anlagen: Model<Anlage>,
@InjectModel(ProConViewAggregate.name, 'anlagen') private readonly graphics: Model<ProConViewAggregate>,
@InjectModel('ProConZuordnung', 'anlagen') private readonly mappings: Model<ProConZuordnung>,
private readonly db: SqlService,
private readonly draw: DrawService,
) {}
private async verifyAggregate(pool: sql.ConnectionPool, aggregateId: number, mapping: ProConZuordnung) {
const result = await pool.request().input('agg', sql.Int, aggregateId).query(`
SELECT a.SPSAntriebId, (SELECT COUNT(*) FROM Aggregate b WHERE b.SPSAntriebId=a.SPSAntriebId) AS Anzahl
FROM Aggregate a WHERE a.Id=@agg`);
const row = result.recordset[0];
if (!row || row.SPSAntriebId !== mapping.spsAntriebId || row.Anzahl !== 1)
throw new BadRequestException('ProCon-IDs haben sich geaendert oder sind mehrdeutig. Unter Zuordnung Vorschlaege neu laden und aktualisieren.');
}
private async loadGroup(aggregateId: number) {
const anlage = await this.anlagen.findOne({ selected: true }).exec();
if (!anlage?.aktiveProConVerbindungId) throw new BadRequestException('Aktive Verbindung fehlt');
const context = { anlageId: anlage._id.toString(), verbindungId: anlage.aktiveProConVerbindungId };
const mapping = await this.mappings.findOne({ ...context, proConAggregateId: aggregateId }).lean().exec();
if (!mapping) throw new BadRequestException('Aggregat zuerst unter ProCon → Zuordnung zuordnen');
const document = await this.graphics.findOne({ visuAggregateId: mapping.visuAggregateId }).exec();
if (!document) throw new BadRequestException('Eigene Grafikelemente fehlen');
const pool = await this.db.getPool(context.anlageId);
await this.verifyAggregate(pool, aggregateId, mapping);
const rows = (await pool.request().input('agg', sql.Int, aggregateId)
.query('SELECT Id, PositionX, PositionY, PositionZ, Width, Height, Show FROM Visualisierungen WHERE AggregateId=@agg ORDER BY Id')).recordset;
const ids = mapping.elemente.map(item => item.elementId);
const remoteIds = mapping.elemente.map(item => item.visualizationId);
if (new Set(ids).size !== ids.length || new Set(remoteIds).size !== remoteIds.length)
throw new BadRequestException('Mehrdeutige Elementzuordnung. Zuordnung prüfen.');
const elements = document.elemente.map(element => {
const id = element._id!.toString();
const link = mapping.elemente.find(item => item.elementId === id);
const row = rows.find(item => item.Id === link?.visualizationId);
return {
id, key: element.key, typ: element.typ,
visualizationId: row ? row.Id as number : null,
local: { z: element.zIndex, x: element.posX, y: element.posY, width: element.width, height: element.height, show: element.show },
procon: row ? { z: row.PositionZ as number, x: row.PositionX as number, y: row.PositionY as number, width: row.Width as number, height: row.Height as number, show: !!row.Show } : null,
svg: element.darstellung === 'xaml' ? element.varianten.find(item => item.svg)?.svg ?? '' : '',
hasXaml: element.darstellung === 'xaml',
generator: element.darstellung === 'xaml' ? element.generator : undefined,
};
});
const main = elements.find(item => item.key === 'main');
const masterId = main?.id ?? document.positionsMasterId ?? '';
const version = createHash('sha256').update(JSON.stringify({
context, mapping, elements: elements.map(({ svg, ...item }) => item), masterId, revision: document.get('__v'),
})).digest('hex');
const current = await this.anlagen.findOne({ selected: true }).exec();
if (current?._id.toString() !== context.anlageId || current.aktiveProConVerbindungId !== context.verbindungId)
throw new BadRequestException('Anlage oder Verbindung geändert. Neu laden.');
return { context, document, pool, elements, masterId, mainId: main?.id ?? null, version };
}
async compareGroup(aggregateId: number) {
const data = await this.loadGroup(aggregateId);
return { ...data.context, elements: data.elements, masterId: data.masterId, mainId: data.mainId, version: data.version };
}
async applyGroup(aggregateId: number, dto: GroupSyncRequest) {
if (!dto || !['saveLocal', 'toLocal', 'toProcon'].includes(dto.direction)) throw new BadRequestException('Ungültige Richtung');
const data = await this.loadGroup(aggregateId);
if (dto.version !== data.version) throw new BadRequestException('Daten geändert. Arbeitsfläche neu laden.');
const masterId = data.mainId ?? dto.masterId;
if (!data.elements.some(item => item.id === masterId)) throw new BadRequestException('Positions-Master auswählen');
if (dto.direction === 'saveLocal') {
if (!Array.isArray(dto.elements) || dto.elements.length !== data.elements.length ||
new Set(dto.elements.map(item => item.id)).size !== data.elements.length ||
dto.elements.some(item => !data.elements.some(element => element.id === item.id)))
throw new BadRequestException('Elementliste unvollständig oder ungültig');
dto.elements.forEach(item => validateGroupValues(item.values));
}
if (dto.direction === 'toProcon') {
if (dto.elementIds !== undefined && (!Array.isArray(dto.elementIds) || !dto.elementIds.length ||
new Set(dto.elementIds).size !== dto.elementIds.length || dto.elementIds.some(id => !data.elements.some(item => item.id === id && item.procon))))
throw new BadRequestException('Ungueltige Elementauswahl fuer ProCon');
const mapped = data.elements.filter(item => item.procon && (!dto.elementIds || dto.elementIds.includes(item.id)));
if (!mapped.length) throw new BadRequestException('Keine zugeordneten ProCon-Visualisierungen');
const transaction = new sql.Transaction(data.pool);
await transaction.begin();
try {
for (const element of mapped) {
const previous = element.procon!;
const values = element.local;
validateGroupValues(values);
const result = await new sql.Request(transaction)
.input('id', sql.Int, element.visualizationId).input('agg', sql.Int, aggregateId)
.input('z', sql.Int, values.z).input('oldZ', sql.Int, previous.z)
.input('x', sql.Float, values.x).input('y', sql.Float, values.y)
.input('w', sql.Float, values.width).input('h', sql.Float, values.height).input('show', sql.Bit, values.show)
.input('oldX', sql.Float, previous.x).input('oldY', sql.Float, previous.y)
.input('oldW', sql.Float, previous.width).input('oldH', sql.Float, previous.height).input('oldShow', sql.Bit, previous.show)
.query(`UPDATE Visualisierungen SET PositionZ=@z,PositionX=@x,PositionY=@y,Width=@w,Height=@h,Show=@show
WHERE Id=@id AND AggregateId=@agg AND PositionZ=@oldZ AND PositionX=@oldX AND PositionY=@oldY AND Width=@oldW AND Height=@oldH AND Show=@oldShow`);
if (result.rowsAffected[0] !== 1) throw new BadRequestException('ProCon inzwischen geändert. Alle Änderungen werden zurückgerollt.');
}
await transaction.commit();
} catch (error) { await transaction.rollback().catch(() => undefined); throw error; }
} else {
for (const element of data.document.elemente) {
const entry = data.elements.find(item => item.id === element._id!.toString())!;
// Importwerte kommen ausschließlich aus der Fremd-DB, niemals aus Eingabefeldern.
const values = dto.direction === 'toLocal' ? entry.procon : dto.elements!.find(item => item.id === entry.id)!.values;
if (!values) continue;
validateGroupValues(values);
const resized = element.width !== values.width || element.height !== values.height;
element.zIndex = values.z; element.posX = values.x; element.posY = values.y; element.width = values.width; element.height = values.height; element.show = values.show;
if (resized) {
element.manuell = true;
if (element.darstellung === 'xaml' && element.generator) element.generator.ergebnis = undefined;
}
const generator = dto.direction === 'saveLocal' ? dto.elements!.find(item => item.id === entry.id)!.generator : undefined;
if (generator !== undefined) {
if (element.darstellung !== 'xaml' || !generator || typeof generator !== 'object')
throw new BadRequestException('Nur XAML-Elemente verwenden einen Grafikgenerator');
const { grafikTyp, config, options } = generator;
const ergebnis = this.draw.renderGraphic(grafikTyp, { config, options });
element.generator = { grafikTyp, config, options: options ?? {}, ergebnis };
element.manuell = false;
element.width = ergebnis.width; element.height = ergebnis.height;
element.varianten = ergebnis.varianten.map(variant => ({
zustand: variant.state, svg: variant.svg, xaml: variant.xaml, xamlBase64: variant.xamlBase64,
}));
}
}
data.document.positionsMasterId = masterId;
data.document.markModified('elemente');
await data.document.validate();
const result = await this.graphics.updateOne({ _id: data.document._id, __v: data.document.get('__v') }, {
$set: { elemente: data.document.toObject().elemente, positionsMasterId: masterId }, $inc: { __v: 1 },
});
if (result.matchedCount !== 1) throw new BadRequestException('Eigene Daten inzwischen geändert. Neu laden.');
}
return this.compareGroup(aggregateId);
}
private async load(aggregateId: number, visualizationId: number) {
const anlage = await this.anlagen.findOne({ selected: true }).exec();
if (!anlage?.aktiveProConVerbindungId) throw new BadRequestException('Aktive Verbindung fehlt');
const context = { anlageId: anlage._id.toString(), verbindungId: anlage.aktiveProConVerbindungId };
const mapping = await this.mappings.findOne({ ...context, proConAggregateId: aggregateId }).lean().exec();
const link = mapping?.elemente.find(item => item.visualizationId === visualizationId);
if (!mapping || !link) throw new BadRequestException('Diese Visualisierung zuerst unter ProCon → Zuordnung zuordnen');
const document = await this.graphics.findOne({ visuAggregateId: mapping.visuAggregateId }).exec();
const element = document?.elemente.find(item => item._id?.toString() === link.elementId);
if (!document || !element) throw new BadRequestException('Zugeordnetes eigenes Element fehlt. Zuordnung prüfen.');
const pool = await this.db.getPool(context.anlageId);
await this.verifyAggregate(pool, aggregateId, mapping);
const remote = await pool.request().input('id', sql.Int, visualizationId).input('agg', sql.Int, aggregateId)
.query('SELECT Id, PositionX, PositionY, Width, Height, Show FROM Visualisierungen WHERE Id=@id AND AggregateId=@agg');
const row = remote.recordset[0];
if (!row) throw new BadRequestException('ProCon-Visualisierung nicht mehr vorhanden');
const views = element.darstellung === 'xaml'
? (await pool.request().input('id', sql.Int, visualizationId).query(`
SELECT DISTINCT v.Id, v.Data,
(SELECT COUNT(*) FROM Komponenten k2 WHERE k2.ViewId=v.Id) AS Verwendungen
FROM Komponenten k JOIN Views v ON v.Id=k.ViewId WHERE k.XamlVisualisierungId=@id ORDER BY v.Id
`)).recordset : [];
const local = { x: element.posX, y: element.posY, width: element.width, height: element.height, show: element.show };
const procon = { x: row.PositionX, y: row.PositionY, width: row.Width, height: row.Height, show: !!row.Show };
const variants = element.darstellung === 'xaml' ? element.varianten.map(item => ({
state: item.zustand, xaml: item.xaml || decodeXaml(item.xamlBase64),
})) : [];
const version = createHash('sha256').update(JSON.stringify({ context, link, local, procon, variants, views })).digest('hex');
const current = await this.anlagen.findOne({ selected: true }).exec();
if (current?._id.toString() !== context.anlageId || current.aktiveProConVerbindungId !== context.verbindungId)
throw new BadRequestException('Anlage oder Verbindung geändert. Neu laden.');
return { pool, document, element, context, local, procon, variants, views, version };
}
async compare(aggregateId: number, visualizationId: number) {
const data = await this.load(aggregateId, visualizationId);
return {
...data.context, version: data.version, key: data.element.key,
local: data.local, procon: data.procon, variants: data.variants,
views: data.views.map(view => ({ id: view.Id as string, xaml: decodeXaml(view.Data), usages: Number(view.Verwendungen) })),
};
}
async apply(aggregateId: number, visualizationId: number, dto: SyncRequest) {
if (!dto || !['toLocal', 'toProcon', 'saveLocal'].includes(dto.direction)) throw new BadRequestException('Ungültige Richtung');
const data = await this.load(aggregateId, visualizationId);
if (dto.version !== data.version) throw new BadRequestException('Daten haben sich geändert. Vergleich neu laden.');
if (dto.xamlOnly && dto.xaml === undefined) throw new BadRequestException('XAML fehlt');
const values = dto.xamlOnly ? (dto.direction === 'toProcon' ? data.procon : data.local)
: dto.direction === 'toLocal' ? data.procon : dto.values;
validateSyncValues(values);
const withXaml = dto.xaml !== undefined;
const xaml = dto.direction === 'toLocal' ? decodeXaml(data.views.find(view => view.Id === dto.viewId)?.Data) : dto.xaml;
if (withXaml && (data.element.darstellung !== 'xaml' || !dto.state || !/^[a-zA-Z0-9_-]+$/.test(dto.state)))
throw new BadRequestException('Eigenen XAML-Zustand auswählen');
if (withXaml && dto.direction !== 'saveLocal' && !data.views.some(view => view.Id === dto.viewId))
throw new BadRequestException('Zugeordnete ProCon-XAML-Datei auswählen');
if (withXaml && (typeof xaml !== 'string' || /<!DOCTYPE|<!ENTITY/i.test(xaml!) || (xaml!.trim() && !xaml!.trimStart().startsWith('<'))))
throw new BadRequestException('XAML muss XML-Text ohne DTD sein');
if (withXaml) validateSyncXml(xaml!);
if (dto.direction === 'toProcon') {
const transaction = new sql.Transaction(data.pool);
await transaction.begin();
try {
const result = await new sql.Request(transaction)
.input('id', sql.Int, visualizationId).input('agg', sql.Int, aggregateId)
.input('x', sql.Float, values.x).input('y', sql.Float, values.y)
.input('w', sql.Float, values.width).input('h', sql.Float, values.height).input('show', sql.Bit, values.show)
.input('oldX', sql.Float, data.procon.x).input('oldY', sql.Float, data.procon.y)
.input('oldW', sql.Float, data.procon.width).input('oldH', sql.Float, data.procon.height).input('oldShow', sql.Bit, data.procon.show)
.query(`UPDATE Visualisierungen SET PositionX=@x,PositionY=@y,Width=@w,Height=@h,Show=@show
WHERE Id=@id AND AggregateId=@agg AND PositionX=@oldX AND PositionY=@oldY AND Width=@oldW AND Height=@oldH AND Show=@oldShow`);
if (result.rowsAffected[0] !== 1) throw new BadRequestException('ProCon-Werte wurden inzwischen geändert. Neu laden.');
if (withXaml) {
const view = data.views.find(view => view.Id === dto.viewId)!;
const update = await new sql.Request(transaction).input('id', sql.NVarChar, dto.viewId)
.input('oldData', sql.NVarChar(sql.MAX), view.Data)
.input('data', sql.NVarChar(sql.MAX), Buffer.from(xaml!, 'utf8').toString('base64'))
.query('UPDATE Views SET Data=@data WHERE Id=@id AND (CONVERT(nvarchar(max),Data)=@oldData OR (Data IS NULL AND @oldData IS NULL))');
if (update.rowsAffected[0] !== 1) throw new BadRequestException('XAML wurde inzwischen geändert. Neu laden.');
}
await transaction.commit();
} catch (error) { await transaction.rollback().catch(() => undefined); throw error; }
} else {
data.element.posX = values.x; data.element.posY = values.y;
data.element.width = values.width; data.element.height = values.height; data.element.show = values.show;
data.element.manuell = true;
if (data.element.darstellung === 'xaml' && data.element.generator) data.element.generator.ergebnis = undefined;
if (withXaml && data.element.darstellung === 'xaml') {
const variant = { zustand: dto.state!, svg: '', xaml: xaml!, xamlBase64: Buffer.from(xaml!, 'utf8').toString('base64') };
const index = data.element.varianten.findIndex(item => item.zustand === dto.state);
if (index < 0) data.element.varianten.push(variant); else data.element.varianten[index] = variant;
// Vorhandenes SVG ist nach manueller XAML-Änderung keine verlässliche Vorschau.
}
data.document.markModified('elemente');
await data.document.validate();
const element = data.document.toObject().elemente.find(item => item._id?.toString() === data.element._id?.toString());
const result = await this.graphics.updateOne({
_id: data.document._id, __v: data.document.get('__v'),
'elemente._id': data.element._id,
}, { $set: { 'elemente.$': element }, $inc: { __v: 1 } });
if (result.matchedCount !== 1) throw new BadRequestException('Eigene Daten wurden inzwischen geändert. Neu laden.');
}
return this.compare(aggregateId, visualizationId);
}
}