visualisierung
This commit is contained in:
1 parent
d0655f3638
commit
367c93c93e
84 files changed
+2265
-148
No files matched your search
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, it, jest } from '@jest/globals';
|
||||
import { Types } from 'mongoose';
|
||||
jest.mock('./aggregate.repository', () => ({ AggregateRepository: class AggregateRepository {} }));
|
||||
jest.mock('../visualisierungen/visualisierungen.service', () => ({ VisualisierungenService: class VisualisierungenService {} }));
|
||||
import { AggregateMappingService } from './aggregate-mapping.service';
|
||||
|
||||
describe('Zuordnung übernehmen', () => {
|
||||
function setup() {
|
||||
const updateOne = jest.fn<() => Promise<{ upsertedCount: number }>>().mockResolvedValue({ upsertedCount: 1 });
|
||||
const service = new AggregateMappingService({} as any, {} as any, {} as any, { updateOne } as any, {} as any, {} as any);
|
||||
const row = {
|
||||
proConAggregateId: 10, spsAntriebId: 44, name: 'Sieb', status: 'eindeutig', visuAggregateId: 'local',
|
||||
localName: 'Sieb', candidates: [], gespeichert: null,
|
||||
elemente: [
|
||||
{ visualizationId: 20, art: 'MotorVisualisierung', xamlNames: [], status: 'eindeutig', candidates: [{ elementId: 'motor-id', key: 'motor' }] },
|
||||
{ visualizationId: 21, art: 'TextVisualisierung', xamlNames: [], status: 'mehrdeutig', candidates: [] },
|
||||
],
|
||||
};
|
||||
const preview = { anlageId: 'anlage', verbindungId: 'test-db', verbindungName: 'Test', version: 'geprüft', rows: [
|
||||
row, { ...row, proConAggregateId: 11, status: 'gespeichert' }, { ...row, proConAggregateId: 12, status: 'mehrdeutig' },
|
||||
] };
|
||||
jest.spyOn(service, 'preview').mockResolvedValue(preview);
|
||||
return { service, updateOne, preview };
|
||||
}
|
||||
it('speichert nur neue eindeutige Treffer und überschreibt keine bestätigten Zuordnungen', async () => {
|
||||
const { service, updateOne, preview } = setup();
|
||||
expect(await service.accept(preview)).toEqual({ count: 1, conflicts: 0 });
|
||||
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||
expect(updateOne).toHaveBeenCalledWith(
|
||||
{ anlageId: 'anlage', verbindungId: 'test-db', proConAggregateId: 10 },
|
||||
{ $setOnInsert: { spsAntriebId: 44, visuAggregateId: 'local', elemente: [{ visualizationId: 20, elementId: 'motor-id', key: 'motor' }] } },
|
||||
{ upsert: true, runValidators: true },
|
||||
);
|
||||
});
|
||||
it('verhindert Übernahme nach Verbindungswechsel oder geänderten Vorschlägen', async () => {
|
||||
const { service, updateOne, preview } = setup();
|
||||
await expect(service.accept({ ...preview, verbindungId: 'produktion' })).rejects.toThrow('geändert');
|
||||
await expect(service.accept({ ...preview, version: 'alt' })).rejects.toThrow('geändert');
|
||||
expect(updateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
it('überspringt gleichzeitig entstandene Eindeutigkeitskonflikte', async () => {
|
||||
const { service, updateOne, preview } = setup();
|
||||
updateOne.mockRejectedValue({ code: 11000 });
|
||||
expect(await service.accept(preview)).toEqual({ count: 0, conflicts: 1 });
|
||||
});
|
||||
it('erkennt neue Aggregate- und Visualisierungs-IDs anhand der SPSAntriebId', async () => {
|
||||
const id = new Types.ObjectId();
|
||||
const query = (value: unknown) => ({ lean: () => ({ exec: async () => value }), exec: async () => value });
|
||||
const stored = { proConAggregateId: 10, spsAntriebId: 44, visuAggregateId: id,
|
||||
elemente: [{ visualizationId: 20, elementId: 'motor-id', key: 'motor' }] };
|
||||
const service = new AggregateMappingService(
|
||||
{ findOne: () => query({ _id: 'anlage', aktiveProConVerbindungId: 'test', proConVerbindungen: [{ _id: 'test', name: 'Test' }] }) } as any,
|
||||
{ find: () => query([{ _id: id, antriebId: 44, antriebName: 'Motor' }]) } as any,
|
||||
{ find: () => query([{ visuAggregateId: id, elemente: [{ _id: 'motor-id', typ: 'motor', key: 'motor' }] }]) } as any,
|
||||
{ find: () => query([stored]) } as any,
|
||||
{ findAll: async () => [{ Id: 100, SPSAntriebId: 44, Bezeichnung: 'Motor' }] } as any,
|
||||
{ getVisuaWithXamlNames: async () => [{ Id: 200, Discriminator: 'MotorVisualisierung', Number: 1, xamlNames: [] }] } as any,
|
||||
);
|
||||
const preview = await service.preview();
|
||||
expect(preview.rows[0].status).toBe('aktualisieren');
|
||||
expect(preview.rows[0].gespeichert?.proConAggregateId).toBe(10);
|
||||
expect(preview.rows[0].elemente[0].visualizationId).toBe(200);
|
||||
});
|
||||
it('aktualisiert bestehende MongoDB-Zuordnungen statt neue anzulegen', async () => {
|
||||
const { service, updateOne, preview } = setup();
|
||||
const row = preview.rows[0];
|
||||
row.status = 'aktualisieren';
|
||||
(row as any).gespeichert = { proConAggregateId: 5, visuAggregateId: 'local', elemente: [] };
|
||||
updateOne.mockResolvedValue({ matchedCount: 1 } as any);
|
||||
expect(await service.accept(preview)).toEqual({ count: 1, conflicts: 0 });
|
||||
expect(updateOne).toHaveBeenCalledWith(expect.objectContaining({ spsAntriebId: 44, proConAggregateId: 5 }),
|
||||
{ $set: { proConAggregateId: 10, elemente: [{ visualizationId: 20, elementId: 'motor-id', key: 'motor' }] } },
|
||||
{ runValidators: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Anlage } from '../../_schemas/anlage.schema';
|
||||
import { VisuAggregate } from '../../_schemas/anlagen/visu-aggregate';
|
||||
import { ProConViewAggregate } from '../../_schemas/anlagen/procon-view-aggregate';
|
||||
import type { ProConZuordnung } from '../../_schemas/anlagen/procon-zuordnung';
|
||||
import { AggregateRepository } from './aggregate.repository';
|
||||
import { VisualisierungenService } from '../visualisierungen/visualisierungen.service';
|
||||
import { matchElements } from './aggregate-matching';
|
||||
|
||||
export interface MappingRow {
|
||||
proConAggregateId: number;
|
||||
spsAntriebId: number;
|
||||
name: string;
|
||||
status: string;
|
||||
visuAggregateId: string;
|
||||
localName: string;
|
||||
candidates: { id: string; name: string }[];
|
||||
elemente: ReturnType<typeof matchElements>;
|
||||
gespeichert: { proConAggregateId?: number; visuAggregateId: string; elemente: ProConZuordnung['elemente'] } | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AggregateMappingService {
|
||||
constructor(
|
||||
@InjectModel(Anlage.name) private readonly anlagen: Model<Anlage>,
|
||||
@InjectModel(VisuAggregate.name, 'anlagen') private readonly local: Model<VisuAggregate>,
|
||||
@InjectModel(ProConViewAggregate.name, 'anlagen') private readonly graphics: Model<ProConViewAggregate>,
|
||||
@InjectModel('ProConZuordnung', 'anlagen') private readonly mappings: Model<ProConZuordnung>,
|
||||
private readonly repo: AggregateRepository,
|
||||
private readonly visu: VisualisierungenService,
|
||||
) {}
|
||||
|
||||
private async context() {
|
||||
const anlage = await this.anlagen.findOne({ selected: true }).exec();
|
||||
const verbindung = anlage?.proConVerbindungen.find(item => item._id.toString() === anlage.aktiveProConVerbindungId);
|
||||
if (!anlage || !verbindung) throw new BadRequestException('Anlage und aktive ProCon-Verbindung auswählen');
|
||||
return { anlageId: anlage._id.toString(), verbindungId: verbindung._id.toString(), verbindungName: verbindung.name };
|
||||
}
|
||||
|
||||
async preview() {
|
||||
const context = await this.context();
|
||||
const [sources, local, stored] = await Promise.all([
|
||||
this.repo.findAll(context.anlageId),
|
||||
this.local.find({ $expr: { $eq: [{ $toString: '$anlageId' }, context.anlageId] } }).lean().exec(),
|
||||
this.mappings.find({ anlageId: context.anlageId, verbindungId: context.verbindungId }).lean().exec(),
|
||||
]);
|
||||
const graphics = await this.graphics.find({ visuAggregateId: { $in: local.map(item => item._id) } }).lean().exec();
|
||||
const rows: MappingRow[] = [];
|
||||
for (const source of sources.sort((a, b) => a.SPSAntriebId - b.SPSAntriebId)) {
|
||||
const candidates = local.filter(item => item.antriebId === source.SPSAntriebId);
|
||||
const stable = stored.filter(item => item.spsAntriebId === source.SPSAntriebId);
|
||||
const existing = stable.length === 1 ? stable[0] : undefined;
|
||||
const unique = candidates.length === 1 && sources.filter(item => item.SPSAntriebId === source.SPSAntriebId).length === 1;
|
||||
const target = unique && (!existing || existing.visuAggregateId.toString() === candidates[0]._id.toString()) ? candidates[0] : undefined;
|
||||
const graphic = target ? graphics.find(item => item.visuAggregateId.toString() === target._id.toString()) : undefined;
|
||||
const elements = target ? matchElements(graphic?.elemente ?? [], await this.visu.getVisuaWithXamlNames(source.Id, context.anlageId), target.view ?? '') : [];
|
||||
const alreadyUsed = target && stored.some(item => item.visuAggregateId.toString() === target._id.toString() && item !== existing);
|
||||
const refreshed = elements.filter(item => item.status === 'eindeutig').map(item => ({ visualizationId: item.visualizationId, ...item.candidates[0] }));
|
||||
const outdated = existing && (existing.proConAggregateId !== source.Id || existing.elemente.some(link =>
|
||||
!elements.some(item => item.visualizationId === link.visualizationId && item.candidates.some(candidate => candidate.elementId === link.elementId))));
|
||||
const repairable = !!target && !alreadyUsed && stable.length === 1 && elements.every(item => item.status !== 'mehrdeutig') &&
|
||||
existing!.elemente.every(link => refreshed.some(item => item.elementId === link.elementId));
|
||||
rows.push({
|
||||
proConAggregateId: source.Id, spsAntriebId: source.SPSAntriebId, name: source.Bezeichnung,
|
||||
status: stable.length > 1 || alreadyUsed || existing && !target ? 'mehrdeutig'
|
||||
: existing ? outdated ? repairable ? 'aktualisieren' : 'mehrdeutig' : 'gespeichert'
|
||||
: unique ? 'eindeutig' : candidates.length ? 'mehrdeutig' : 'fehlt',
|
||||
visuAggregateId: target?._id.toString() ?? '',
|
||||
localName: target?.antriebName ?? '',
|
||||
candidates: candidates.map(item => ({ id: item._id.toString(), name: item.antriebName })),
|
||||
elemente: elements,
|
||||
gespeichert: existing ? { proConAggregateId: existing.proConAggregateId, visuAggregateId: existing.visuAggregateId.toString(), elemente: existing.elemente } : null,
|
||||
});
|
||||
}
|
||||
const current = await this.context();
|
||||
if (current.anlageId !== context.anlageId || current.verbindungId !== context.verbindungId)
|
||||
throw new BadRequestException('Anlage oder Verbindung hat sich geändert. Bitte neu laden.');
|
||||
const version = createHash('sha256').update(JSON.stringify({ context, rows })).digest('hex');
|
||||
return { ...context, rows, version };
|
||||
}
|
||||
|
||||
async accept(dto: { anlageId: string; verbindungId: string; version: string }) {
|
||||
const preview = await this.preview();
|
||||
if (!dto || dto.anlageId !== preview.anlageId || dto.verbindungId !== preview.verbindungId || dto.version !== preview.version)
|
||||
throw new BadRequestException('Zuordnungsvorschläge haben sich geändert. Bitte Vorschläge neu laden und prüfen.');
|
||||
let count = 0;
|
||||
let conflicts = 0;
|
||||
for (const row of preview.rows.filter(item => item.status === 'eindeutig' || item.status === 'aktualisieren')) {
|
||||
try {
|
||||
const elemente = row.elemente.filter(item => item.status === 'eindeutig').map(item => ({ visualizationId: item.visualizationId, ...item.candidates[0] }));
|
||||
if (row.status === 'aktualisieren') {
|
||||
const result = await this.mappings.updateOne({
|
||||
anlageId: preview.anlageId, verbindungId: preview.verbindungId, spsAntriebId: row.spsAntriebId,
|
||||
proConAggregateId: row.gespeichert!.proConAggregateId, visuAggregateId: row.visuAggregateId,
|
||||
elemente: row.gespeichert!.elemente,
|
||||
}, { $set: { proConAggregateId: row.proConAggregateId, elemente } }, { runValidators: true });
|
||||
if (result.matchedCount === 1) count++; else conflicts++;
|
||||
continue;
|
||||
}
|
||||
const result = await this.mappings.updateOne({
|
||||
anlageId: preview.anlageId, verbindungId: preview.verbindungId, proConAggregateId: row.proConAggregateId,
|
||||
}, { $setOnInsert: {
|
||||
spsAntriebId: row.spsAntriebId, visuAggregateId: row.visuAggregateId,
|
||||
elemente: row.elemente.filter(item => item.status === 'eindeutig').map(item => ({
|
||||
visualizationId: item.visualizationId, ...item.candidates[0],
|
||||
})),
|
||||
} }, { upsert: true, runValidators: true });
|
||||
count += result.upsertedCount;
|
||||
} catch (error) {
|
||||
if ((error as { code?: number }).code === 11000) conflicts++;
|
||||
else throw error;
|
||||
}
|
||||
}
|
||||
return { count, conflicts };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from '@jest/globals';
|
||||
import { matchElements } from './aggregate-matching';
|
||||
|
||||
describe('ProCon Elementzuordnung', () => {
|
||||
const element = (key: string, typ: string) => ({ key, typ, _id: { toString: () => key + '-id' } });
|
||||
it('ordnet Motoren anhand ihrer Nummer und Standardelemente anhand ihres Typs zu', () => {
|
||||
const rows = matchElements([element('motor', 'motor'), element('motor2', 'motor'), element('text', 'text')], [
|
||||
{ Id: 1, Discriminator: 'MotorVisualisierung', Number: 2, xamlNames: [] },
|
||||
{ Id: 2, Discriminator: 'TextVisualisierung', xamlNames: [] },
|
||||
], '');
|
||||
expect(rows.map(row => row.status)).toEqual(['eindeutig', 'eindeutig']);
|
||||
expect(rows[0].candidates[0].key).toBe('motor2');
|
||||
});
|
||||
it('ordnet main über den XAML-Dateinamen zu und verwechselt keine Pfeilnummern', () => {
|
||||
const rows = matchElements([element('main', 'main'), element('pfeil1', 'pfeil'), element('pfeil10', 'pfeil')], [
|
||||
{ Id: 1, Discriminator: 'XamlVisualisierung', xamlNames: ['G_Band_Main_Active.xaml', 'G_Band_Main_Inactive.xaml'] },
|
||||
{ Id: 2, Discriminator: 'XamlVisualisierung', xamlNames: ['G_Band_pfeil10_error.xaml'] },
|
||||
], 'G_Band');
|
||||
expect(rows[0].candidates.map(item => item.key)).toEqual(['main']);
|
||||
expect(rows[1].candidates.map(item => item.key)).toEqual(['pfeil10']);
|
||||
});
|
||||
it('meldet fehlende und mehrdeutige Zuordnungen statt willkürlich auszuwählen', () => {
|
||||
const rows = matchElements([element('text', 'text'), element('text2', 'text')], [
|
||||
{ Id: 1, Discriminator: 'TextVisualisierung', xamlNames: [] },
|
||||
{ Id: 2, Discriminator: 'MotorVisualisierung', Number: 1, xamlNames: [] },
|
||||
], '');
|
||||
expect(rows.map(row => row.status)).toEqual(['mehrdeutig', 'fehlt']);
|
||||
});
|
||||
it('verhindert die mehrfache Verwendung desselben Elements', () => {
|
||||
const rows = matchElements([element('text', 'text')], [
|
||||
{ Id: 1, Discriminator: 'TextVisualisierung', xamlNames: [] },
|
||||
{ Id: 2, Discriminator: 'TextVisualisierung', xamlNames: [] },
|
||||
], '');
|
||||
expect(rows.every(row => row.status === 'mehrdeutig')).toBe(true);
|
||||
});
|
||||
it('ordnet Warnung ohne MinMax.xaml ohne Zustandszusatz dem Warnungselement zu', () => {
|
||||
const rows = matchElements([element('warnung', 'warnung'), element('main', 'main')], [
|
||||
{ Id: 30, Discriminator: 'XamlVisualisierung', xamlNames: ['Warnung ohne MinMax.xaml'] },
|
||||
], 'G_Band');
|
||||
expect(rows[0].status).toBe('eindeutig');
|
||||
expect(rows[0].candidates.map(item => item.key)).toEqual(['warnung']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
export interface MatchingElement { _id?: { toString(): string }; key: string; typ: string }
|
||||
export interface MatchingVisualization { Id: number; Discriminator: string; Number?: number; xamlNames: string[] }
|
||||
|
||||
export function matchElements(elements: MatchingElement[], visualizations: MatchingVisualization[], view: string) {
|
||||
const types: Record<string, string> = {
|
||||
motor: 'MotorVisualisierung', anfahrzeit: 'AnfahrZeitVisualisierung',
|
||||
betriebsart: 'BetriebsArtVisualisierung', text: 'TextVisualisierung',
|
||||
};
|
||||
const rows = visualizations.map(visualization => {
|
||||
const candidates = elements.filter(element => {
|
||||
const discriminator = types[element.typ];
|
||||
if (discriminator) {
|
||||
if (visualization.Discriminator !== discriminator) return false;
|
||||
if (element.typ !== 'motor') return true;
|
||||
const number = /^motor(\d*)$/i.exec(element.key);
|
||||
return !!number && visualization.Number === Number(number[1] || 1);
|
||||
}
|
||||
if (visualization.Discriminator !== 'XamlVisualisierung') return false;
|
||||
return visualization.xamlNames.some(filename => {
|
||||
const base = filename.replace(/\.xaml$/i, '').toLowerCase();
|
||||
if (element.typ === 'warnung' && base === 'warnung ohne minmax') return true;
|
||||
const exact = view && base.startsWith((view + '_' + element.key + '_').toLowerCase());
|
||||
// Nur vollständige Element-Tokens, keine Teiltreffer wie pfeil1/pfeil10.
|
||||
const legacy = new RegExp('_(?:' + (element.key === 'main' ? 'main' : element.key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + ')_(?:active|inactive|error|inactivepos[01])$', 'i');
|
||||
return exact || legacy.test(base);
|
||||
});
|
||||
});
|
||||
return {
|
||||
visualizationId: visualization.Id, art: visualization.Discriminator,
|
||||
xamlNames: visualization.xamlNames,
|
||||
candidates: candidates.map(element => ({ elementId: element._id?.toString() ?? '', key: element.key })),
|
||||
status: candidates.length === 1 && !!candidates[0]._id ? 'eindeutig' : candidates.length > 1 ? 'mehrdeutig' : 'fehlt',
|
||||
};
|
||||
});
|
||||
// Ein eigenes Element darf nicht mehreren ProCon-Visualisierungen zugeordnet werden.
|
||||
for (const row of rows) {
|
||||
if (row.status === 'eindeutig' && rows.filter(other => other.candidates.some(candidate => candidate.elementId === row.candidates[0].elementId)).length > 1)
|
||||
row.status = 'mehrdeutig';
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -1,15 +1,47 @@
|
||||
import { Controller, Get, Param } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, ParseIntPipe, Post, HttpCode } from '@nestjs/common';
|
||||
import { AggregateMappingService } from './aggregate-mapping.service';
|
||||
import { AggregateService } from './aggregate.service';
|
||||
import { ProConSyncService } from './procon-sync.service';
|
||||
import type { SyncRequest } from './procon-sync.service';
|
||||
import type { GroupSyncRequest } from './procon-sync.service';
|
||||
|
||||
@Controller('procon/aggregate')
|
||||
export class AggregateController {
|
||||
constructor(private readonly service: AggregateService) { }
|
||||
constructor(private readonly service: AggregateService, private readonly mapping: AggregateMappingService, private readonly sync: ProConSyncService) { }
|
||||
|
||||
@Get(':id/arbeitsflaeche')
|
||||
compareGroup(@Param('id', ParseIntPipe) id: number) { return this.sync.compareGroup(id); }
|
||||
|
||||
@Post(':id/arbeitsflaeche')
|
||||
@HttpCode(200)
|
||||
applyGroup(@Param('id', ParseIntPipe) id: number, @Body() dto: GroupSyncRequest) { return this.sync.applyGroup(id, dto); }
|
||||
|
||||
@Get(':id/visualisierungen/:visuId/sync')
|
||||
compare(@Param('id', ParseIntPipe) id: number, @Param('visuId', ParseIntPipe) visuId: number) { return this.sync.compare(id, visuId); }
|
||||
|
||||
@Post(':id/visualisierungen/:visuId/sync')
|
||||
@HttpCode(200)
|
||||
apply(@Param('id', ParseIntPipe) id: number, @Param('visuId', ParseIntPipe) visuId: number, @Body() dto: SyncRequest) {
|
||||
return this.sync.apply(id, visuId, dto);
|
||||
}
|
||||
|
||||
@Get('zuordnung')
|
||||
preview() { return this.mapping.preview(); }
|
||||
|
||||
@Post('zuordnung')
|
||||
@HttpCode(200)
|
||||
accept(@Body() dto: { anlageId: string; verbindungId: string; version: string }) { return this.mapping.accept(dto); }
|
||||
|
||||
@Get()
|
||||
getAll() {
|
||||
return this.service.getAllAggregate();
|
||||
}
|
||||
|
||||
@Get(':id/visualisierungen')
|
||||
getVisualisierungen(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.service.getVisualisierungen(id);
|
||||
}
|
||||
|
||||
@Get('/byId/:id')
|
||||
getAggregateById(@Param('id') id: number) {
|
||||
return this.service.getById(id);
|
||||
|
||||
@@ -5,13 +5,28 @@ import { SqlModule } from 'src/infrastructure/sql/sql.module';
|
||||
import { AggregateRepository } from './aggregate.repository';
|
||||
import { VisualisierungenService } from '../visualisierungen/visualisierungen.service';
|
||||
import { VisualisierungenModule } from '../visualisierungen/visualisierungen.module';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { Anlage, AnlageSchema } from '../../_schemas/anlage.schema';
|
||||
import { VisuAggregate, VisuAggregateSchema } from '../../_schemas/anlagen/visu-aggregate';
|
||||
import { ProConViewAggregate, ProConViewAggregateSchema } from '../../_schemas/anlagen/procon-view-aggregate';
|
||||
import { ProConZuordnungSchema } from '../../_schemas/anlagen/procon-zuordnung';
|
||||
import { AggregateMappingService } from './aggregate-mapping.service';
|
||||
import { ProConSyncService } from './procon-sync.service';
|
||||
import { DrawModule } from '../../draw/draw.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
DrawModule,
|
||||
MongooseModule.forFeature([{ name: Anlage.name, schema: AnlageSchema }]),
|
||||
MongooseModule.forFeature([
|
||||
{ name: VisuAggregate.name, schema: VisuAggregateSchema },
|
||||
{ name: ProConViewAggregate.name, schema: ProConViewAggregateSchema },
|
||||
{ name: 'ProConZuordnung', schema: ProConZuordnungSchema },
|
||||
], 'anlagen'),
|
||||
SqlModule,
|
||||
VisualisierungenModule
|
||||
],
|
||||
providers: [AggregateService,AggregateRepository],
|
||||
providers: [AggregateService,AggregateRepository, AggregateMappingService, ProConSyncService],
|
||||
controllers: [AggregateController]
|
||||
})
|
||||
export class AggregateModule { }
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { ProConAggregateEntity } from "src/_sql/procon.Aggregat.entity";
|
||||
import { SqlService } from "src/infrastructure/sql/sql.service";
|
||||
import * as sql from 'mssql';
|
||||
|
||||
@Injectable()
|
||||
export class AggregateRepository {
|
||||
@@ -27,13 +28,14 @@ export class AggregateRepository {
|
||||
const pool = await this.db.getPool(anlageId);
|
||||
|
||||
let where = "";
|
||||
if (options.id) where += `id=${options.id}`;
|
||||
if (options.SPSAntriebId) where += `SPSAntriebId=${options.SPSAntriebId}`;
|
||||
if (options.id !== undefined) where = 'Id=@id';
|
||||
if (options.SPSAntriebId !== undefined) where = 'SPSAntriebId=@id';
|
||||
|
||||
if (where === "" || options.id && options.SPSAntriebId) return undefined;
|
||||
if (where === "" || (options.id !== undefined && options.SPSAntriebId !== undefined)) return undefined;
|
||||
|
||||
const result = await pool
|
||||
.request()
|
||||
.input('id', sql.Int, options.id ?? options.SPSAntriebId)
|
||||
.query(`
|
||||
SELECT *
|
||||
FROM Aggregate
|
||||
@@ -43,4 +45,4 @@ export class AggregateRepository {
|
||||
return result.recordset[0];
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { AggregateRepository } from './aggregate.repository';
|
||||
import { VisualisierungenService } from '../visualisierungen/visualisierungen.service';
|
||||
|
||||
@@ -14,6 +14,12 @@ export class AggregateService {
|
||||
return this.repo.findAll(this.anlage)
|
||||
}
|
||||
|
||||
async getVisualisierungen(id: number) {
|
||||
const aggregat = await this.repo.findBy(this.anlage, { id });
|
||||
if (!aggregat) throw new NotFoundException('Aggregat nicht gefunden');
|
||||
return { aggregat, visualisierungen: await this.visuService.getVisuaWithXamlNames(aggregat.Id) };
|
||||
}
|
||||
|
||||
async getById(id:number){
|
||||
const agg = await this.repo.findBy(this.anlage,{id:id});
|
||||
if(!agg) return {success:false,error:"Aggregat nicht gefunden"}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
|
||||
jest.mock('../../infrastructure/sql/sql.service', () => ({ SqlService: class SqlService {} }));
|
||||
jest.mock('../../draw/draw.service', () => ({ DrawService: class DrawService {} }));
|
||||
jest.mock('mssql', () => {
|
||||
const actual = jest.requireActual('mssql') as object;
|
||||
return { ...actual, Transaction: jest.fn(), Request: jest.fn() };
|
||||
});
|
||||
import * as sql from 'mssql';
|
||||
import { model, Types } from 'mongoose';
|
||||
import { ProConViewAggregateSchema } from '../../_schemas/anlagen/procon-view-aggregate';
|
||||
import { ProConSyncService, decodeXaml } from './procon-sync.service';
|
||||
import { validateSyncXml } from './sync-xml';
|
||||
|
||||
describe('Einzelsynchronisierung', () => {
|
||||
const View = model('SyncViewTest', ProConViewAggregateSchema);
|
||||
let service: ProConSyncService, data: any, updates: any, transaction: any, requests: any[];
|
||||
beforeEach(() => {
|
||||
const document = new View({ visuAggregateId: new Types.ObjectId(), elemente: [{
|
||||
key: 'main', name: '', darstellung: 'xaml', typ: 'main', width: 20, height: 20,
|
||||
posX: 5, posY: 5, zIndex: 2, show: true,
|
||||
varianten: [{ zustand: 'inactive', svg: '<svg/>', xaml: '<Viewbox/>', xamlBase64: 'PFZpZXdib3gvPg==' }],
|
||||
}] });
|
||||
data = { pool: {}, document, element: document.elemente[0], context: {},
|
||||
version: 'reviewed', local: {}, procon: { z: 7, x: 5, y: 5, width: 20, height: 20, show: true },
|
||||
variants: [], views: [{ Id: 'Warnung.xaml', Data: 'alt', Verwendungen: 2 }] };
|
||||
updates = { updateOne: jest.fn<() => Promise<unknown>>().mockResolvedValue({ matchedCount: 1 }) };
|
||||
service = new ProConSyncService({} as any, updates, {} as any, {} as any, {
|
||||
renderGraphic: jest.fn(() => ({ width: 50, height: 60, varianten: [{
|
||||
state: 'inactive', svg: '<svg/>', xaml: '<Viewbox/>', xamlBase64: 'PFZpZXdib3gvPg==',
|
||||
}] })),
|
||||
} as any);
|
||||
jest.spyOn(service as any, 'load').mockResolvedValue(data);
|
||||
jest.spyOn(service, 'compare').mockResolvedValue({ version: 'after' } as any);
|
||||
transaction = {
|
||||
begin: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
commit: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
rollback: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
};
|
||||
(sql.Transaction as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => transaction);
|
||||
requests = [];
|
||||
(sql.Request as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => {
|
||||
const request: any = { query: jest.fn<() => Promise<unknown>>().mockResolvedValue({ rowsAffected: [1] }) };
|
||||
request.input = jest.fn(() => request);
|
||||
requests.push(request); return request;
|
||||
});
|
||||
});
|
||||
|
||||
const values = { z: 0, x: 0, y: 0, width: 30, height: 40, show: false };
|
||||
it('übernimmt 0 und false nach MongoDB und hält XAML/Base64 konsistent', async () => {
|
||||
data.procon = values;
|
||||
data.views[0].Data = Buffer.from('<Viewbox><Canvas/></Viewbox>').toString('base64');
|
||||
await service.apply(1, 2, { version: 'reviewed', direction: 'toLocal', values: { ...values, x: 999 },
|
||||
state: 'inactive', viewId: 'Warnung.xaml', xaml: '<Viewbox><Canvas/></Viewbox>' });
|
||||
expect(data.element.posX).toBe(0);
|
||||
expect(data.element.show).toBe(false);
|
||||
expect(data.element.manuell).toBe(true);
|
||||
expect(data.element.varianten[0].svg).toBe('');
|
||||
expect(decodeXaml(data.element.varianten[0].xamlBase64)).toBe('<Viewbox><Canvas/></Viewbox>');
|
||||
expect(updates.updateOne).toHaveBeenCalledWith(expect.objectContaining({ 'elemente._id': data.element._id }), expect.objectContaining({ $inc: { __v: 1 } }));
|
||||
});
|
||||
it('schreibt Position und Base64-XAML zusammen in einer SQL-Transaktion', async () => {
|
||||
await service.apply(1, 2, { version: 'reviewed', direction: 'toProcon', values,
|
||||
state: 'inactive', viewId: 'Warnung.xaml', xaml: '<Viewbox/>' });
|
||||
expect(transaction.commit).toHaveBeenCalled();
|
||||
expect(transaction.rollback).not.toHaveBeenCalled();
|
||||
expect(requests[0].input).toHaveBeenCalledWith('x', sql.Float, 0);
|
||||
expect(requests[0].input).toHaveBeenCalledWith('show', sql.Bit, false);
|
||||
expect(requests[1].input).toHaveBeenCalledWith('data', expect.anything(), Buffer.from('<Viewbox/>').toString('base64'));
|
||||
expect(updates.updateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
it('verhindert veraltete Vergleiche, ungültige Werte und unzugeordnete Views', async () => {
|
||||
await expect(service.apply(1, 2, { version: 'old', direction: 'toProcon', values })).rejects.toThrow('geändert');
|
||||
await expect(service.apply(1, 2, { version: 'reviewed', direction: 'saveLocal', values: { ...values, width: -1 } })).rejects.toThrow('Zahlen');
|
||||
await expect(service.apply(1, 2, { version: 'reviewed', direction: 'toProcon', values, state: 'inactive', viewId: 'fremd', xaml: '<Viewbox/>' })).rejects.toThrow('ProCon-XAML');
|
||||
expect(updates.updateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
it('erkennt konkurrierende Änderungen in MongoDB', async () => {
|
||||
updates.updateOne.mockResolvedValue({ matchedCount: 0 });
|
||||
await expect(service.apply(1, 2, { version: 'reviewed', direction: 'saveLocal', values })).rejects.toThrow('inzwischen geändert');
|
||||
});
|
||||
it('rollt bei einem SQL-Konflikt alle Änderungen zurück', async () => {
|
||||
(sql.Request as unknown as ReturnType<typeof jest.fn>).mockImplementationOnce(() => {
|
||||
const request: any = { query: jest.fn<() => Promise<unknown>>().mockResolvedValue({ rowsAffected: [0] }) };
|
||||
request.input = jest.fn(() => request);
|
||||
return request;
|
||||
});
|
||||
await expect(service.apply(1, 2, { version: 'reviewed', direction: 'toProcon', values })).rejects.toThrow('inzwischen geändert');
|
||||
expect(transaction.rollback).toHaveBeenCalled();
|
||||
expect(transaction.commit).not.toHaveBeenCalled();
|
||||
});
|
||||
function group() {
|
||||
const id = data.element._id.toString();
|
||||
data.elements = [{ id, local: values, procon: data.procon, visualizationId: 2 }];
|
||||
data.mainId = id;
|
||||
jest.spyOn(service as any, 'loadGroup').mockResolvedValue(data);
|
||||
jest.spyOn(service, 'compareGroup').mockResolvedValue({ version: 'after' } as any);
|
||||
return id;
|
||||
}
|
||||
it('importiert Gruppenwerte aus ProCon und ignoriert Clientwerte', async () => {
|
||||
const id = group();
|
||||
await service.applyGroup(1, { version: 'reviewed', direction: 'toLocal', masterId: 'wrong', elements: [{ id, values }] });
|
||||
expect(data.element.posX).toBe(5);
|
||||
expect(data.element.zIndex).toBe(7);
|
||||
expect(data.document.positionsMasterId).toBe(id);
|
||||
expect(updates.updateOne).toHaveBeenCalled();
|
||||
});
|
||||
it('exportiert gespeicherte Gruppenwerte statt Clientwerten', async () => {
|
||||
const id = group();
|
||||
await service.applyGroup(1, { version: 'reviewed', direction: 'toProcon', masterId: id, elements: [{ id, values: { ...values, x: 999 } }] });
|
||||
expect(requests[0].input).toHaveBeenCalledWith('x', sql.Float, 0);
|
||||
expect(requests[0].input).toHaveBeenCalledWith('z', sql.Int, 0);
|
||||
expect(requests[0].input).toHaveBeenCalledWith('oldZ', sql.Int, 7);
|
||||
expect(transaction.commit).toHaveBeenCalled();
|
||||
});
|
||||
it('verlangt ohne main einen vorhandenen Master und eine komplette Liste', async () => {
|
||||
const id = group(); data.mainId = null;
|
||||
await expect(service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: 'missing', elements: [] })).rejects.toThrow();
|
||||
await expect(service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: id, elements: [] })).rejects.toThrow();
|
||||
expect(updates.updateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
it('speichert Z-Index 0 und weist ungueltige Ebenen ab', async () => {
|
||||
const id = group();
|
||||
await expect(service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: id, elements: [{ id, values: { ...values, z: 1.5 } }] })).rejects.toThrow('Z-Index');
|
||||
await service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: id, elements: [{ id, values }] });
|
||||
expect(data.element.zIndex).toBe(0);
|
||||
});
|
||||
it('erzeugt geaenderte Grafiken serverseitig und behaelt Position und Ebene', async () => {
|
||||
const id = group();
|
||||
await service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: id,
|
||||
elements: [{ id, values, generator: { grafikTyp: 'warnung', config: { width: 50, height: 60 }, options: {} } }] });
|
||||
expect(data.element.width).toBe(50);
|
||||
expect(data.element.height).toBe(60);
|
||||
expect(data.element.posX).toBe(values.x);
|
||||
expect(data.element.zIndex).toBe(values.z);
|
||||
expect(data.element.manuell).toBe(false);
|
||||
expect(data.element.varianten[0].xamlBase64).toBe('PFZpZXdib3gvPg==');
|
||||
expect(data.element.generator.ergebnis.width).toBe(50);
|
||||
});
|
||||
it('sperrt wiederverwendete Aggregate-IDs mit anderer SPSAntriebId', async () => {
|
||||
const request: any = { query: async () => ({ recordset: [{ SPSAntriebId: 55, Anzahl: 1 }] }) };
|
||||
request.input = () => request;
|
||||
await expect((service as any).verifyAggregate({ request: () => request }, 10, { spsAntriebId: 44 })).rejects.toThrow('Zuordnung');
|
||||
});
|
||||
it('synchronisiert nur die gefilterte Elementauswahl', async () => {
|
||||
const id = group();
|
||||
data.elements.push({ id: 'hidden', local: { ...values, x: 500 }, procon: data.procon, visualizationId: 3 });
|
||||
await service.applyGroup(1, { version: 'reviewed', direction: 'toProcon', masterId: id, elementIds: [id] });
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].input).toHaveBeenCalledWith('id', sql.Int, 2);
|
||||
expect(transaction.commit).toHaveBeenCalled();
|
||||
});
|
||||
it('weist fremde oder leere Elementauswahlen vor dem Schreiben ab', async () => {
|
||||
const id = group();
|
||||
for (const elementIds of [[], ['unknown'], [id, id]]) {
|
||||
await expect(service.applyGroup(1, { version: 'reviewed', direction: 'toProcon', masterId: id, elementIds })).rejects.toThrow('Elementauswahl');
|
||||
}
|
||||
expect(transaction.begin).not.toHaveBeenCalled();
|
||||
});
|
||||
it('dekodiert UTF-8-Base64 und akzeptiert bereits lesbares XAML', () => {
|
||||
const xml = '<TextBlock Text="Förderer"/>';
|
||||
expect(decodeXaml(Buffer.from(xml).toString('base64'))).toBe(xml);
|
||||
expect(decodeXaml(xml)).toBe(xml);
|
||||
});
|
||||
it.each(['<Viewbox><Canvas/></Viewbox>', '<?xml version="1.0"?><Viewbox xmlns="test"><!--ok--><Canvas/></Viewbox>', ''])('akzeptiert XML %s', xml => {
|
||||
expect(() => validateSyncXml(xml)).not.toThrow();
|
||||
});
|
||||
it.each(['<Viewbox><Canvas></Viewbox>', '<Viewbox/><Canvas/>', '<Viewbox Width=20/>', '<!DOCTYPE x><Viewbox/>'])('weist ungültiges XML zurück %s', xml => {
|
||||
expect(() => validateSyncXml(xml)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
// Strukturprüfung ohne Ausführung von XAML, Ressourcen oder externen Entitäten.
|
||||
export function validateSyncXml(xml: string) {
|
||||
if (!xml.trim()) return;
|
||||
const invalid = () => { throw new BadRequestException('XAML enthält ungültiges XML'); };
|
||||
if (/<!DOCTYPE|<!ENTITY/i.test(xml)) invalid();
|
||||
const stack: string[] = [];
|
||||
let roots = 0;
|
||||
let position = 0;
|
||||
const tokens = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<\/?[A-Za-z_][\w:.-]*(?:[^<>"']|"[^"]*"|'[^']*')*>/g;
|
||||
for (const match of xml.matchAll(tokens)) {
|
||||
const text = xml.slice(position, match.index);
|
||||
if (text.includes('<') || (!stack.length && text.trim())) invalid();
|
||||
const token = match[0];
|
||||
position = match.index! + token.length;
|
||||
if (token.startsWith('<!--') || token.startsWith('<?')) continue;
|
||||
if (token.startsWith('<![CDATA[')) { if (!stack.length) invalid(); continue; }
|
||||
const tag = /^<(\/?)([A-Za-z_][\w:.-]*)([\s\S]*?)(\/?)>$/.exec(token);
|
||||
if (!tag) invalid();
|
||||
const [, closing, name, attributes, selfClosing] = tag!;
|
||||
if (closing) {
|
||||
if (attributes.trim() || selfClosing || stack.pop() !== name) invalid();
|
||||
} else {
|
||||
const names = new Set<string>();
|
||||
const rest = attributes.replace(/\s+([A-Za-z_][\w:.-]*)\s*=\s*("[^"]*"|'[^']*')/g, (_, key: string) => {
|
||||
if (names.has(key)) invalid();
|
||||
names.add(key); return '';
|
||||
});
|
||||
if (rest.trim()) invalid();
|
||||
if (!stack.length && ++roots > 1) invalid();
|
||||
if (!selfClosing) stack.push(name);
|
||||
}
|
||||
}
|
||||
if (stack.length || roots !== 1 || xml.slice(position).trim()) invalid();
|
||||
}
|
||||
@@ -9,8 +9,8 @@ export class KomponentenService {
|
||||
private readonly repo: KomponentenRepository,
|
||||
) { }
|
||||
|
||||
async getKomponenten(xamlVisuId: number) {
|
||||
const komponenten = await this.repo.findBy(this.anlage, xamlVisuId);
|
||||
async getKomponenten(xamlVisuId: number, anlage: string = this.anlage) {
|
||||
const komponenten = await this.repo.findBy(anlage, xamlVisuId);
|
||||
|
||||
return komponenten;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Injectable } from "@nestjs/common";
|
||||
import { ProConAggregateEntity } from "src/_sql/procon.Aggregat.entity";
|
||||
import { ProConVisualisierungenAggEntity, ProConVisualisierungenEntity } from "src/_sql/procon.Visualisierung.entity";
|
||||
import { SqlService } from "src/infrastructure/sql/sql.service";
|
||||
import * as sql from 'mssql';
|
||||
|
||||
@Injectable()
|
||||
export class VisualisierungenRepository {
|
||||
@@ -27,7 +28,8 @@ export class VisualisierungenRepository {
|
||||
AggregateId,
|
||||
Number,
|
||||
PositionZ`
|
||||
const result = await pool.request().query(`SELECT ${fields} FROM Visualisierungen where AggregateId=${aggId}`);
|
||||
const result = await pool.request().input('aggregateId', sql.Int, aggId)
|
||||
.query(`SELECT ${fields} FROM Visualisierungen WHERE AggregateId=@aggregateId ORDER BY PositionZ, Id`);
|
||||
|
||||
return result.recordset;
|
||||
}
|
||||
@@ -71,4 +73,4 @@ export class VisualisierungenRepository {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,16 @@ export class VisualisierungenService {
|
||||
return this.repo.getVisuaOfAgg(this.anlage, aggId)
|
||||
}
|
||||
|
||||
async getVisuaWithXamlNames(aggId: number, anlage: string = this.anlage) {
|
||||
const visualisierungen = await this.repo.getVisuaOfAgg(anlage, aggId);
|
||||
return Promise.all(visualisierungen.map(async item => ({
|
||||
...item,
|
||||
xamlNames: item.Discriminator === 'XamlVisualisierung'
|
||||
? [...new Set((await this.komponentenService.getKomponenten(item.Id, anlage)).map(component => component.ViewId).filter(Boolean))]
|
||||
: [],
|
||||
})));
|
||||
}
|
||||
|
||||
async updateMongoDB(aggId: number) {
|
||||
/* const sqlAggData = await this.getVisuaAggData(aggId);
|
||||
if (!sqlAggData) return;
|
||||
|
||||
Reference in new issue
Block a user