diff --git a/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_active.xaml b/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_active.xaml index 1dd1710..ac72361 100644 --- a/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_active.xaml +++ b/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_active.xaml @@ -1,16 +1,16 @@ - - + + 0.5,0.5 - - - + + + - + diff --git a/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_error.xaml b/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_error.xaml index a34b880..e0d75da 100644 --- a/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_error.xaml +++ b/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_error.xaml @@ -1,16 +1,16 @@ - - + + 0.5,0.5 - - - + + + - + diff --git a/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_inactive.xaml index 5338fe9..bab3382 100644 --- a/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_inactive.xaml +++ b/data/1667_Durmin 2/xaml/BA1_26_Zufuhrband_M_main_inactive.xaml @@ -1,9 +1,15 @@ - - - + + + + + 0.5,0.5 + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_main_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_main_inactive.xaml index a68871a..e5e8454 100644 --- a/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_main_inactive.xaml +++ b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_main_inactive.xaml @@ -1,12 +1,17 @@ - - - - - - + + + + + 0.5,0.5 + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_active.xaml b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_active.xaml new file mode 100644 index 0000000..d624b5a --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_active.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_error.xaml b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_error.xaml new file mode 100644 index 0000000..31a4690 --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_error.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_inactive.xaml new file mode 100644 index 0000000..462c5cc --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_28_Verteilband_M1_visuMot_inactive.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_active.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_active.xaml index b271198..cd31f35 100644 --- a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_active.xaml +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_active.xaml @@ -1,18 +1,18 @@ - - + + 0.5,0.5 - - - - - - + + + + + + - + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_error.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_error.xaml index 799e543..daa180d 100644 --- a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_error.xaml +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_error.xaml @@ -1,18 +1,18 @@ - - + + 0.5,0.5 - - - - - - + + + + + + - + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_inactive.xaml index f1c7fc9..82da091 100644 --- a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_inactive.xaml +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_main_inactive.xaml @@ -1,16 +1,16 @@ - - + + 0.5,0.5 - - - - - - + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_active.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_active.xaml new file mode 100644 index 0000000..b328dbd --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_active.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_error.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_error.xaml new file mode 100644 index 0000000..db689d2 --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_error.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_inactive.xaml new file mode 100644 index 0000000..e5c5fc2 --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_1_inactive.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_active.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_active.xaml new file mode 100644 index 0000000..f477f83 --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_active.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_error.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_error.xaml new file mode 100644 index 0000000..8bbf607 --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_error.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_inactive.xaml new file mode 100644 index 0000000..f8f68a5 --- /dev/null +++ b/data/1667_Durmin 2/xaml/BA1_29_Kopfband_hinten_M_pfeil_2_inactive.xaml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_active.xaml b/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_active.xaml index b271198..cd31f35 100644 --- a/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_active.xaml +++ b/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_active.xaml @@ -1,18 +1,18 @@ - - + + 0.5,0.5 - - - - - - + + + + + + - + diff --git a/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_error.xaml b/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_error.xaml index 799e543..daa180d 100644 --- a/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_error.xaml +++ b/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_error.xaml @@ -1,18 +1,18 @@ - - + + 0.5,0.5 - - - - - - + + + + + + - + diff --git a/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_inactive.xaml b/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_inactive.xaml index f1c7fc9..82da091 100644 --- a/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_inactive.xaml +++ b/data/1667_Durmin 2/xaml/BA1_30_Kopfband_vorne_M_main_inactive.xaml @@ -1,16 +1,16 @@ - - + + 0.5,0.5 - - - - - - + + + + + + diff --git a/src/_dto/draw.dto.ts b/src/_dto/draw.dto.ts index 789dff1..e7b863e 100644 --- a/src/_dto/draw.dto.ts +++ b/src/_dto/draw.dto.ts @@ -27,7 +27,7 @@ export class DrawDataDto { name!:string; height!: number; width!:number; - varianten!: { state: 'inactive' | 'active' | 'error'; svg: string; xaml: string; xamlBase64: string }[]; + varianten!: { state: string; svg: string; xaml: string; xamlBase64: string }[]; } export class DrawShapeOptionenDto{ diff --git a/src/_dto/pfeil.dto.ts b/src/_dto/pfeil.dto.ts new file mode 100644 index 0000000..df79362 --- /dev/null +++ b/src/_dto/pfeil.dto.ts @@ -0,0 +1,32 @@ +import { BadRequestException } from '@nestjs/common'; + +export interface PfeilVariant { name: string; state: 'active' | 'inactive' | 'error'; reverse?: boolean } +export interface PfeilConfig { points: { x: number; y: number }[]; variants?: PfeilVariant[] } +export interface PfeilOptions { colorInactive?: string; colorActive?: string; colorError?: string } + +export function parsePfeilRequest(input: unknown): { config: PfeilConfig; options: PfeilOptions } { + const object = (value: unknown): value is Record => !!value && typeof value === 'object' && !Array.isArray(value); + if (!object(input) || Object.keys(input).some(key => !['config', 'options'].includes(key)) || !object(input.config)) + throw new BadRequestException('Erwartet werden config und optional options'); + const points = input.config.points; + if (Object.keys(input.config).some(key => !['points', 'variants'].includes(key)) || !Array.isArray(points) || points.length < 2 || points.length > 1000 || + points.some(point => !object(point) || Object.keys(point).some(key => !['x', 'y'].includes(key)) || + [point.x, point.y].some(value => typeof value !== 'number' || !Number.isFinite(value) || Math.abs(value) > 1000000))) + throw new BadRequestException('Pfeil benötigt 2 bis 1000 Punkte mit endlichen Koordinaten zwischen -1000000 und 1000000'); + const typed = points as PfeilConfig['points']; + if (!typed.some(point => point.x !== typed[0].x || point.y !== typed[0].y)) + throw new BadRequestException('Pfeil benötigt mindestens zwei unterschiedliche Punkte'); + const variants = input.config.variants; + if (variants !== undefined && (!Array.isArray(variants) || !variants.length || variants.length > 100 || variants.some(variant => + !object(variant) || Object.keys(variant).some(key => !['name', 'state', 'reverse'].includes(key)) || + typeof variant.name !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(variant.name) || + !['active', 'inactive', 'error'].includes(String(variant.state)) || + (variant.reverse !== undefined && typeof variant.reverse !== 'boolean')) || + new Set(variants.map(variant => variant.name.toLowerCase())).size !== variants.length)) + throw new BadRequestException('Varianten benötigen eindeutige Dateinamen (Buchstaben, Zahlen, _ und -), einen Grundzustand active/inactive/error und optional reverse'); + const options = input.options ?? {}; + if (!object(options) || Object.entries(options).some(([key, value]) => + !['colorInactive', 'colorActive', 'colorError'].includes(key) || typeof value !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(value))) + throw new BadRequestException('Pfeilfarben müssen Hexfarben #RRGGBB sein'); + return { config: { points: typed.map(({ x, y }) => ({ x, y })), ...(variants !== undefined ? { variants: variants as PfeilVariant[] } : {}) }, options }; +} diff --git a/src/_schemas/anlagen/procon-view-aggregate.ts b/src/_schemas/anlagen/procon-view-aggregate.ts index dfce9a0..a5b94f9 100644 --- a/src/_schemas/anlagen/procon-view-aggregate.ts +++ b/src/_schemas/anlagen/procon-view-aggregate.ts @@ -4,7 +4,7 @@ import { VisuAggregate } from './visu-aggregate'; import type { DrawDataDto } from '../../_dto/draw.dto'; export interface GrafikGeneratorDaten { - grafikTyp: 'motor' | 'bandOben' | 'warnung'; + grafikTyp: 'motor' | 'bandOben' | 'warnung' | 'pfeil'; config: Record; options: Record; ergebnis?: DrawDataDto; @@ -88,7 +88,7 @@ const elemente = ProConViewAggregateSchema.path ({}) }, ergebnis: { type: MongooseSchema.Types.Mixed }, diff --git a/src/_schemas/anlagen/procon-zuordnung.ts b/src/_schemas/anlagen/procon-zuordnung.ts index 0952cee..53bbd37 100644 --- a/src/_schemas/anlagen/procon-zuordnung.ts +++ b/src/_schemas/anlagen/procon-zuordnung.ts @@ -5,7 +5,8 @@ export interface ProConZuordnung { proConAggregateId: number; spsAntriebId: number; visuAggregateId: Types.ObjectId; - elemente: { visualizationId: number; elementId: string; key: string }[]; + elemente: { visualizationId: number; elementId: string; key: string; manuell?: boolean }[]; + ausgeschlosseneVisualisierungen?: number[]; } export const ProConZuordnungSchema = new Schema({ anlageId: { type: String, required: true }, @@ -13,7 +14,8 @@ export const ProConZuordnungSchema = new Schema({ proConAggregateId: { type: Number, required: true }, spsAntriebId: { type: Number, required: true }, visuAggregateId: { type: Schema.Types.ObjectId, required: true, ref: 'VisuAggregate' }, - elemente: { type: [new Schema({ visualizationId: Number, elementId: String, key: String }, { _id: false })], default: [] }, + elemente: { type: [new Schema({ visualizationId: Number, elementId: String, key: String, manuell: Boolean }, { _id: false })], default: [] }, + ausgeschlosseneVisualisierungen: { type: [Number], default: [] }, }, { collection: 'procon_zuordnungen', timestamps: true }); ProConZuordnungSchema.index({ anlageId: 1, verbindungId: 1, proConAggregateId: 1 }, { unique: true }); ProConZuordnungSchema.index({ anlageId: 1, verbindungId: 1, visuAggregateId: 1 }, { unique: true }); diff --git a/src/anlagen/visu-aggregate/procon-view-aggregate.service.ts b/src/anlagen/visu-aggregate/procon-view-aggregate.service.ts index a5e646a..2907fcc 100644 --- a/src/anlagen/visu-aggregate/procon-view-aggregate.service.ts +++ b/src/anlagen/visu-aggregate/procon-view-aggregate.service.ts @@ -38,6 +38,19 @@ export class ProConViewAggregateService { !item || typeof item.componentId !== 'string' || !Array.isArray(item.elementKeys) || item.elementKeys.some(key => typeof key !== 'string'))) throw new BadRequestException('Keine gültige Grafikauswahl'); const aggregates = await this.findAll(); + // Editierbare Pfeile für die gewählte Exportauswahl aus ihren Punkten erzeugen. + for (const selection of dto.auswahl) { + const aggregate = aggregates.find(item => item.componentId === selection.componentId); + if (!aggregate) continue; + for (const element of aggregate.elemente) { + if (!selection.elementKeys.includes(element.key) || element.darstellung !== 'xaml' || + element.generator?.grafikTyp !== 'pfeil' || element.manuell) continue; + const { config, options } = element.generator; + element.varianten = this.draw.renderGraphic('pfeil', { config, options }).varianten.map(variant => ({ + zustand: variant.state, svg: variant.svg, xaml: variant.xaml, xamlBase64: variant.xamlBase64, + })); + } + } if ((await this.anlagen.getSelected()).id !== anlageId) throw new BadRequestException('Anlage hat sich geändert. Bitte neu laden.'); const { files, skipped } = createXamlFiles(aggregates, dto); const safeName = anlage.name.trim() diff --git a/src/draw/draw.service.ts b/src/draw/draw.service.ts index 0e5b17e..aa192d5 100644 --- a/src/draw/draw.service.ts +++ b/src/draw/draw.service.ts @@ -1,5 +1,6 @@ import { Injectable, NotFoundException } from '@nestjs/common'; import { parseMotorRequest } from '../_dto/motor.dto'; +import { parsePfeilRequest } from '../_dto/pfeil.dto'; import { DrawWarnung, parseWarnungRequest } from '../graphics/elements/drawWarnung'; import { DrawShapeOptionenDto } from 'src/_dto/draw.dto'; import { DrawBand } from 'src/graphics/elements/drawBand'; @@ -68,6 +69,10 @@ export class DrawService { renderGraphic(type: string, input: unknown) { switch (type) { + case 'pfeil': { + const { config, options } = parsePfeilRequest(input); + return this.buildPfeil.getObject(config, options); + } case 'warnung': { const { config, options } = parseWarnungRequest(input); return this.buildWarnung.getObject(config, options); diff --git a/src/graphics/elements/drawPfeil.spec.ts b/src/graphics/elements/drawPfeil.spec.ts new file mode 100644 index 0000000..7871d26 --- /dev/null +++ b/src/graphics/elements/drawPfeil.spec.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from '@jest/globals'; +import { DrawPfeil } from './drawPfeil'; +import { parsePfeilRequest } from '../../_dto/pfeil.dto'; +import { createXamlFiles } from '../../anlagen/visu-aggregate/procon-xaml-export'; + +describe('Pfeilgenerator', () => { + it('exportiert frei kombinierte Namen mit zugehöriger Farbe und umgekehrter Richtung', () => { + const request = parsePfeilRequest({ config: { points: [{ x: 6, y: 6 }, { x: 86, y: 6 }], variants: [ + { name: 'activeRight', state: 'active' }, { name: 'activeLeft', state: 'active', reverse: true }, + { name: 'InactivePos1', state: 'inactive' }, { name: 'InactivePos2', state: 'inactive' }, + { name: 'errorRightPos2', state: 'error' }, + ] }, options: { colorActive: '#123456', colorInactive: '#654321', colorError: '#ff0000' } }); + const result = new DrawPfeil().getObject(request.config, request.options); + expect(result.varianten.map(v => v.state)).toEqual(['activeRight', 'activeLeft', 'InactivePos1', 'InactivePos2', 'errorRightPos2']); + expect(result.varianten[0].svg).toContain('#123456'); + expect(result.varianten[1].svg).not.toEqual(result.varianten[0].svg); + expect(result.varianten[2].svg).toContain('#654321'); + expect(result.varianten[4].svg).toContain('#ff0000'); + const exported = createXamlFiles([{ componentId: 'c1', viewName: 'Band', elemente: [{ + key: 'pfeil_1', name: '', typ: 'pfeil', darstellung: 'xaml', posX: 0, posY: 0, width: result.width, height: result.height, zIndex: 0, show: true, + varianten: result.varianten.map(v => ({ zustand: v.state, xaml: v.xaml, xamlBase64: v.xamlBase64 })), + }] }], { anlageId: 'a1', auswahl: [{ componentId: 'c1', elementKeys: ['pfeil_1'] }] }); + expect(exported.files.map(file => file.name)).toEqual(request.config.variants!.map(v => `Band_pfeil_1_${v.name}.xaml`)); + }); + it.each([ + [], [{ name: '../active', state: 'active' }], [{ name: 'a', state: 'unknown' }], + [{ name: 'ActivePos1', state: 'active' }, { name: 'activepos1', state: 'inactive' }], + [{ name: 'active', state: 'active', reverse: 'true' }], + ])('weist ungültige Varianten zurück: %j', (...variants) => { + expect(() => parsePfeilRequest({ config: { points: [{ x: 0, y: 0 }, { x: 10, y: 10 }], variants } })).toThrow(); + }); + it.each([ + [{ x: 0, y: 0 }, { x: 100, y: 0 }], + [{ x: -100, y: -50 }, { x: 0, y: -50 }, { x: 20, y: 20 }, { x: 20, y: 20 }], + [{ x: 0, y: 0 }, { x: 0, y: -100 }], + ])('rendert Punkte %j in allen Zuständen ohne ungültige Geometrie', (...points) => { + const request = parsePfeilRequest({ config: { points }, options: { colorActive: '#123456' } }); + const result = new DrawPfeil().getObject(request.config, request.options); + expect(result.width).toBeGreaterThan(0); expect(result.height).toBeGreaterThan(0); + expect(result.varianten.map(v => v.state)).toEqual(['inactive', 'active', 'error']); + for (const variant of result.varianten) { + expect(variant.svg).toContain(' { + expect(() => parsePfeilRequest({ config: { points } })).toThrow(); + }); + + it('exportiert mehrere Pfeile des Aggregats mit eindeutigen Zustandsdateien', () => { + const result = new DrawPfeil().getObject({ points: [{ x: 6, y: 6 }, { x: 86, y: 46 }] }); + const elemente = ['pfeil_1', 'pfeil_2'].map(key => ({ + key, name: key, typ: 'pfeil', darstellung: 'xaml' as const, width: result.width, height: result.height, + posX: 0, posY: 0, zIndex: 1, show: true, + varianten: result.varianten.map(v => ({ zustand: v.state, xaml: v.xaml, xamlBase64: v.xamlBase64 })), + })); + const exported = createXamlFiles([{ componentId: 'c1', viewName: 'Band', elemente }], + { anlageId: 'a1', auswahl: [{ componentId: 'c1', elementKeys: ['pfeil_1', 'pfeil_2'] }] }); + expect(exported.files).toHaveLength(6); + expect(exported.files[0].name).toBe('Band_pfeil_1_inactive.xaml'); + expect(exported.files.every(file => file.data.includes(' !i || p.x !== all[i - 1].x || p.y !== all[i - 1].y); + const minX = Math.min(0, ...sourcePoints.map(p => p.x - 6)), minY = Math.min(0, ...sourcePoints.map(p => p.y - 6)); + const width = Math.max(...sourcePoints.map(p => p.x + 6)) - minX; + const height = Math.max(...sourcePoints.map(p => p.y + 6)) - minY; + const variants = config.variants ?? (['inactive', 'active', 'error'] as const).map(state => ({ name: state, state, reverse: false })); + const varianten = variants.map(variant => { + const points = variant.reverse ? [...sourcePoints].reverse() : sourcePoints; + const end = points[points.length - 1], previous = points[points.length - 2]; + const distance = Math.hypot(end.x - previous.x, end.y - previous.y); + const ux = (end.x - previous.x) / distance, uy = (end.y - previous.y) / distance; + const size = Math.min(8, distance); + const base = { x: end.x - ux * size, y: end.y - uy * size }; + const state = variant.state; + const color = state === 'active' ? options.colorActive ?? this.gemisch + : state === 'error' ? options.colorError ?? this.red : options.colorInactive ?? this.normal; + const group = new DrawGroup({}); + const line = new DrawPath(points.map((p, i) => ({ type: i ? 'L' : 'M', x: p.x - minX, y: p.y - minY }))); + line.setAtrr({ stroke: color, strokeWidth: 3 }); + const head = new DrawPath([ + { type: 'M', x: base.x - uy * 4 - minX, y: base.y + ux * 4 - minY }, + { type: 'L', x: end.x - minX, y: end.y - minY }, + { type: 'L', x: base.x + uy * 4 - minX, y: base.y - ux * 4 - minY }, { type: 'Z' }, + ]); + head.setAtrr({ fill: color, stroke: color, strokeWidth: 1 }); + group.add(head); group.add(line); + const header = new DrawHeader({ lenght: width, height }); header.add(group); + const svg = header.getChildString(false, 0), xaml = header.getChildString(true, 0); + return { state: variant.name, svg, xaml, xamlBase64: Buffer.from(xaml, 'utf8').toString('base64') }; + }); + return { name: 'pfeil', width, height, varianten }; + } scale = 0; winkel = 0; raster = 4; diff --git a/src/procon/aggregate/aggregate-mapping.service.spec.ts b/src/procon/aggregate/aggregate-mapping.service.spec.ts index 1cb1a17..8c4c06e 100644 --- a/src/procon/aggregate/aggregate-mapping.service.spec.ts +++ b/src/procon/aggregate/aggregate-mapping.service.spec.ts @@ -10,7 +10,7 @@ describe('Zuordnung übernehmen', () => { 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, + localName: 'Sieb', candidates: [], eigeneElemente: [], gespeichert: null, elemente: [ { visualizationId: 20, art: 'MotorVisualisierung', xamlNames: [], status: 'eindeutig', candidates: [{ elementId: 'motor-id', key: 'motor' }] }, { visualizationId: 21, art: 'TextVisualisierung', xamlNames: [], status: 'mehrdeutig', candidates: [] }, @@ -32,6 +32,57 @@ describe('Zuordnung übernehmen', () => { { upsert: true, runValidators: true }, ); }); + function manualSetup() { + const result = setup(); + const row = result.preview.rows[0] as any; + row.status = 'gespeichert'; row.eigeneElemente = [{ elementId: 'arrow-id', key: 'pfeil_1', typ: 'pfeil' }]; + row.gespeichert = { proConAggregateId: 10, visuAggregateId: 'local', elemente: [ + { visualizationId: 20, elementId: 'motor-id', key: 'motor' }, + ], ausgeschlosseneVisualisierungen: [22] }; + row.elemente.push({ visualizationId: 22, art: 'XamlVisualisierung', candidates: [], status: 'ignoriert', xamlNames: ['Fremd.xaml'] }); + result.updateOne.mockResolvedValue({ matchedCount: 1 } as any); + const request = { anlageId: result.preview.anlageId, verbindungId: result.preview.verbindungId, version: result.preview.version, + proConAggregateId: 10, visualizationId: 22, action: 'assign' as const, elementId: 'arrow-id' }; + return { ...result, row, request }; + } + it('ordnet Pfeile manuell zu und hebt einen vorherigen Ausschluss auf', async () => { + const { service, updateOne, request } = manualSetup(); + await expect(service.changeElement(request)).resolves.toEqual({ success: true }); + expect(updateOne).toHaveBeenCalledWith(expect.objectContaining({ anlageId: 'anlage', verbindungId: 'test-db', proConAggregateId: 10 }), { + $set: { elemente: [{ visualizationId: 20, elementId: 'motor-id', key: 'motor' }, + { visualizationId: 22, elementId: 'arrow-id', key: 'pfeil_1', manuell: true }], ausgeschlosseneVisualisierungen: [] }, + }, { runValidators: true }); + }); + it('löscht nur die ausgewählte Verknüpfung und schließt sie vom automatischen Abgleich aus', async () => { + const { service, updateOne, request } = manualSetup(); + await service.changeElement({ ...request, visualizationId: 20, action: 'remove' }); + expect(updateOne).toHaveBeenCalledWith(expect.anything(), { $set: { elemente: [], ausgeschlosseneVisualisierungen: [22, 20] } }, { runValidators: true }); + }); + it('verhindert fremde Elemente, falsche Typen, Doppelzuordnungen und veraltete Vorschläge', async () => { + const { service, updateOne, row, request } = manualSetup(); + await expect(service.changeElement({ ...request, version: 'alt' })).rejects.toThrow('geändert'); + await expect(service.changeElement({ ...request, elementId: 'fremd' })).rejects.toThrow('Eigenen Pfeil'); + await expect(service.changeElement({ ...request, visualizationId: 20 })).rejects.toThrow('Eigenen Pfeil'); + row.gespeichert.elemente.push({ visualizationId: 23, elementId: 'arrow-id', key: 'pfeil_1' }); + await expect(service.changeElement(request)).rejects.toThrow('bereits zugeordnet'); + expect(updateOne).not.toHaveBeenCalled(); + }); + it('erkennt konkurrierende Änderungen beim manuellen Speichern', async () => { + const { service, updateOne, request } = manualSetup(); + updateOne.mockResolvedValue({ matchedCount: 0 } as any); + await expect(service.changeElement(request)).rejects.toThrow('inzwischen geändert'); + }); + it('erhält manuelle Verknüpfungen auch bei einer automatischen Aktualisierung', async () => { + const { service, updateOne, row, preview } = manualSetup(); + row.status = 'aktualisieren'; + row.gespeichert.elemente.push({ visualizationId: 22, elementId: 'arrow-id', key: 'pfeil_1', manuell: true }); + row.elemente[2] = { visualizationId: 22, art: 'XamlVisualisierung', xamlNames: ['Fremd.xaml'], status: 'eindeutig', + candidates: [{ elementId: 'arrow-id', key: 'pfeil_1' }] }; + await service.accept(preview); + const update = (updateOne.mock.calls as any)[0][1]; + expect(update.$set.elemente).toContainEqual({ visualizationId: 22, elementId: 'arrow-id', key: 'pfeil_1', manuell: true }); + expect(update.$set).not.toHaveProperty('ausgeschlosseneVisualisierungen'); + }); 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'); @@ -72,4 +123,28 @@ describe('Zuordnung übernehmen', () => { { $set: { proConAggregateId: 10, elemente: [{ visualizationId: 20, elementId: 'motor-id', key: 'motor' }] } }, { runValidators: true }); }); + it.each([false, true])('zeigt neue lokale Pfeile auch bei gespeicherten Zuordnungen (ProCon-Pfeil: %s)', async remoteArrow => { + 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: 'Band', view: 'Band' }]) } as any, + { find: () => query([{ visuAggregateId: id, elemente: [ + { _id: 'motor-id', typ: 'motor', key: 'motor' }, { _id: 'arrow-id', typ: 'pfeil', key: 'pfeil_1' }, + ] }]) } as any, + { find: () => query([stored]) } as any, + { findAll: async () => [{ Id: 10, SPSAntriebId: 44, Bezeichnung: 'Band' }] } as any, + { getVisuaWithXamlNames: async () => [ + { Id: 20, Discriminator: 'MotorVisualisierung', Number: 1, xamlNames: [] }, + ...(remoteArrow ? [{ Id: 21, Discriminator: 'XamlVisualisierung', xamlNames: ['Band_pfeil_1_active.xaml'] }] : []), + ] } as any, + ); + const row = (await service.preview()).rows[0]; + expect(row.eigeneElemente).toContainEqual({ elementId: 'arrow-id', key: 'pfeil_1', typ: 'pfeil' }); + expect(row.status).toBe(remoteArrow ? 'aktualisieren' : 'gespeichert'); + expect(row.gespeichert?.elemente).toEqual(stored.elemente); + if (remoteArrow) expect(row.elemente[1].candidates[0].elementId).toBe('arrow-id'); + }); }); diff --git a/src/procon/aggregate/aggregate-mapping.service.ts b/src/procon/aggregate/aggregate-mapping.service.ts index 0192618..3fd39f3 100644 --- a/src/procon/aggregate/aggregate-mapping.service.ts +++ b/src/procon/aggregate/aggregate-mapping.service.ts @@ -8,7 +8,13 @@ import { ProConViewAggregate } from '../../_schemas/anlagen/procon-view-aggregat import type { ProConZuordnung } from '../../_schemas/anlagen/procon-zuordnung'; import { AggregateRepository } from './aggregate.repository'; import { VisualisierungenService } from '../visualisierungen/visualisierungen.service'; -import { matchElements } from './aggregate-matching'; +import { matchElements, matchMappedElements } from './aggregate-matching'; + +export interface ElementMappingRequest { + anlageId: string; verbindungId: string; version: string; + proConAggregateId: number; visualizationId: number; + action: 'assign' | 'remove'; elementId?: string; +} export interface MappingRow { proConAggregateId: number; @@ -19,7 +25,8 @@ export interface MappingRow { localName: string; candidates: { id: string; name: string }[]; elemente: ReturnType; - gespeichert: { proConAggregateId?: number; visuAggregateId: string; elemente: ProConZuordnung['elemente'] } | null; + eigeneElemente: { elementId: string; key: string; typ: string }[]; + gespeichert: { proConAggregateId?: number; visuAggregateId: string; elemente: ProConZuordnung['elemente']; ausgeschlosseneVisualisierungen?: number[] } | null; } @Injectable() @@ -56,10 +63,11 @@ export class AggregateMappingService { 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 elements = target ? matchMappedElements(graphic?.elemente ?? [], await this.visu.getVisuaWithXamlNames(source.Id, context.anlageId), target.view ?? '', existing) : []; 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 => + const outdated = existing && (existing.proConAggregateId !== source.Id || + refreshed.some(link => !existing.elemente.some(saved => saved.elementId === link.elementId && saved.visualizationId === link.visualizationId)) || 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)); @@ -72,7 +80,9 @@ export class AggregateMappingService { 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, + eigeneElemente: (graphic?.elemente ?? []).map(element => ({ elementId: element._id?.toString() ?? '', key: element.key, typ: element.typ })), + gespeichert: existing ? { proConAggregateId: existing.proConAggregateId, visuAggregateId: existing.visuAggregateId.toString(), elemente: existing.elemente, + ausgeschlosseneVisualisierungen: existing.ausgeschlosseneVisualisierungen } : null, }); } const current = await this.context(); @@ -90,7 +100,9 @@ export class AggregateMappingService { 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] })); + const elemente = row.elemente.filter(item => item.status === 'eindeutig').map(item => ({ visualizationId: item.visualizationId, ...item.candidates[0], + ...(row.gespeichert?.elemente.some(link => link.manuell && link.elementId === item.candidates[0].elementId) ? { manuell: true } : {}), + })); if (row.status === 'aktualisieren') { const result = await this.mappings.updateOne({ anlageId: preview.anlageId, verbindungId: preview.verbindungId, spsAntriebId: row.spsAntriebId, @@ -116,4 +128,38 @@ export class AggregateMappingService { } return { count, conflicts }; } + + async changeElement(dto: ElementMappingRequest) { + if (!dto || !['assign', 'remove'].includes(dto.action) || !Number.isSafeInteger(dto.proConAggregateId) || !Number.isSafeInteger(dto.visualizationId)) + throw new BadRequestException('Ungültige Elementzuordnung'); + const preview = await this.preview(); + if (dto.anlageId !== preview.anlageId || dto.verbindungId !== preview.verbindungId || dto.version !== preview.version) + throw new BadRequestException('Zuordnungen geändert. Bitte Vorschläge neu laden.'); + const row = preview.rows.find(row => row.proConAggregateId === dto.proConAggregateId); + const saved = row?.gespeichert; + if (!row || !saved || !row.visuAggregateId || row.visuAggregateId !== saved.visuAggregateId || saved.proConAggregateId !== row.proConAggregateId) + throw new BadRequestException('Zuerst eine eindeutige Aggregat-Zuordnung anlegen oder aktualisieren'); + let elemente = saved.elemente.filter(link => link.visualizationId !== dto.visualizationId); + const excluded = new Set(saved.ausgeschlosseneVisualisierungen ?? []); + if (dto.action === 'assign') { + const element = row.eigeneElemente.find(element => element.elementId === dto.elementId && element.typ === 'pfeil'); + const remote = row.elemente.find(remote => remote.visualizationId === dto.visualizationId && remote.art === 'XamlVisualisierung'); + if (!element || !remote) throw new BadRequestException('Eigenen Pfeil und XAML-Visualisierung dieses Aggregats auswählen'); + if (elemente.some(link => link.elementId === element.elementId)) throw new BadRequestException('Pfeil ist bereits zugeordnet. Bestehende Zuordnung zuerst löschen.'); + elemente.push({ visualizationId: dto.visualizationId, elementId: element.elementId, key: element.key, manuell: true }); + excluded.delete(dto.visualizationId); + } else { + if (!saved.elemente.some(link => link.visualizationId === dto.visualizationId)) throw new BadRequestException('Zuordnung nicht mehr vorhanden'); + // Gelöschte Verknüpfungen beim nächsten automatischen Abgleich nicht erneut anlegen. + excluded.add(dto.visualizationId); + } + const result = await this.mappings.updateOne({ + anlageId: preview.anlageId, verbindungId: preview.verbindungId, proConAggregateId: row.proConAggregateId, + visuAggregateId: row.visuAggregateId, elemente: saved.elemente, + ...(saved.ausgeschlosseneVisualisierungen === undefined ? { ausgeschlosseneVisualisierungen: { $exists: false } } + : { ausgeschlosseneVisualisierungen: saved.ausgeschlosseneVisualisierungen }), + }, { $set: { elemente, ausgeschlosseneVisualisierungen: [...excluded] } }, { runValidators: true }); + if (result.matchedCount !== 1) throw new BadRequestException('Zuordnung inzwischen geändert. Bitte neu laden.'); + return { success: true }; + } } diff --git a/src/procon/aggregate/aggregate-matching.spec.ts b/src/procon/aggregate/aggregate-matching.spec.ts index fd5d37e..d659843 100644 --- a/src/procon/aggregate/aggregate-matching.spec.ts +++ b/src/procon/aggregate/aggregate-matching.spec.ts @@ -1,8 +1,31 @@ import { describe, expect, it } from '@jest/globals'; -import { matchElements } from './aggregate-matching'; +import { matchElements, matchMappedElements } from './aggregate-matching'; describe('ProCon Elementzuordnung', () => { const element = (key: string, typ: string) => ({ key, typ, _id: { toString: () => key + '-id' } }); + it('erkennt Pfeile mit Richtungs- und Positionszuständen auch über ältere View-Namen', () => { + for (const state of ['activeRight', 'activeLeft', 'InactivePos1', 'InactivePos2', 'errorRightPos2']) { + const rows = matchElements([element('pfeil_1', 'pfeil'), element('pfeil_10', 'pfeil')], [ + { Id: 1, Discriminator: 'XamlVisualisierung', xamlNames: [`Alt_pfeil_1_${state}.xaml`] }, + ], 'Neu'); + expect(rows[0].status).toBe('eindeutig'); expect(rows[0].candidates[0].key).toBe('pfeil_1'); + } + }); + it('behält manuelle Pfeilzuordnungen ohne passenden Dateinamen bei und reserviert das Element', () => { + const rows = matchMappedElements([element('pfeil_1', 'pfeil')], [ + { Id: 1, Discriminator: 'XamlVisualisierung', xamlNames: ['Anderer_Name.xaml'] }, + { Id: 2, Discriminator: 'XamlVisualisierung', xamlNames: ['Band_pfeil_1_active.xaml'] }, + ], 'Band', { elemente: [{ visualizationId: 1, elementId: 'pfeil_1-id', key: 'pfeil_1', manuell: true }] }); + expect(rows[0].status).toBe('eindeutig'); + expect(rows[0].candidates[0].key).toBe('pfeil_1'); + expect(rows[1].candidates).toEqual([]); + }); + it('legt bewusst gelöschte Zuordnungen nicht automatisch erneut an', () => { + const rows = matchMappedElements([element('pfeil_1', 'pfeil')], [ + { Id: 1, Discriminator: 'XamlVisualisierung', xamlNames: ['Band_pfeil_1_active.xaml'] }, + ], 'Band', { elemente: [], ausgeschlosseneVisualisierungen: [1] }); + expect(rows[0].status).toBe('ignoriert'); expect(rows[0].candidates).toEqual([]); + }); 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: [] }, diff --git a/src/procon/aggregate/aggregate-matching.ts b/src/procon/aggregate/aggregate-matching.ts index 5d7d087..afd833e 100644 --- a/src/procon/aggregate/aggregate-matching.ts +++ b/src/procon/aggregate/aggregate-matching.ts @@ -1,6 +1,25 @@ export interface MatchingElement { _id?: { toString(): string }; key: string; typ: string } export interface MatchingVisualization { Id: number; Discriminator: string; Number?: number; xamlNames: string[] } +export function matchMappedElements(elements: MatchingElement[], visualizations: MatchingVisualization[], view: string, + saved?: { elemente: { visualizationId: number; elementId: string; key: string; manuell?: boolean }[]; ausgeschlosseneVisualisierungen?: number[] }) { + const rows = matchElements(elements, visualizations, view); + const manual = saved?.elemente.filter(link => link.manuell && elements.some(element => element._id?.toString() === link.elementId && element.typ === 'pfeil') && + visualizations.some(remote => remote.Id === link.visualizationId && remote.Discriminator === 'XamlVisualisierung')) ?? []; + for (const row of rows) { + const link = manual.find(link => link.visualizationId === row.visualizationId); + if (saved?.ausgeschlosseneVisualisierungen?.includes(row.visualizationId)) { + row.candidates = []; row.status = 'ignoriert'; continue; + } + row.candidates = link ? [{ elementId: link.elementId, key: link.key }] + : row.candidates.filter(candidate => !manual.some(link => link.elementId === candidate.elementId)); + row.status = row.candidates.length === 1 && !!row.candidates[0].elementId ? 'eindeutig' : row.candidates.length > 1 ? 'mehrdeutig' : 'fehlt'; + } + for (const row of rows) if (row.status === 'eindeutig' && rows.some(other => other !== row && other.candidates.some(candidate => candidate.elementId === row.candidates[0].elementId))) + row.status = 'mehrdeutig'; + return rows; +} + export function matchElements(elements: MatchingElement[], visualizations: MatchingVisualization[], view: string) { const types: Record = { motor: 'MotorVisualisierung', anfahrzeit: 'AnfahrZeitVisualisierung', @@ -21,7 +40,7 @@ export function matchElements(elements: MatchingElement[], visualizations: Match 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'); + const legacy = new RegExp('_(?:' + (element.key === 'main' ? 'main' : element.key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + ')_(?:active|inactive|error)[a-z0-9_-]*$', 'i'); return exact || legacy.test(base); }); }); diff --git a/src/procon/aggregate/aggregate.controller.ts b/src/procon/aggregate/aggregate.controller.ts index 778ca26..580fefb 100644 --- a/src/procon/aggregate/aggregate.controller.ts +++ b/src/procon/aggregate/aggregate.controller.ts @@ -1,5 +1,6 @@ import { Body, Controller, Get, Param, ParseIntPipe, Post, HttpCode } from '@nestjs/common'; import { AggregateMappingService } from './aggregate-mapping.service'; +import type { ElementMappingRequest } from './aggregate-mapping.service'; import { AggregateService } from './aggregate.service'; import { ProConSyncService } from './procon-sync.service'; import type { SyncRequest } from './procon-sync.service'; @@ -28,6 +29,10 @@ export class AggregateController { @Get('zuordnung') preview() { return this.mapping.preview(); } + @Post('zuordnung/element') + @HttpCode(200) + changeElementMapping(@Body() dto: ElementMappingRequest) { return this.mapping.changeElement(dto); } + @Post('zuordnung') @HttpCode(200) accept(@Body() dto: { anlageId: string; verbindungId: string; version: string }) { return this.mapping.accept(dto); } diff --git a/src/procon/aggregate/procon-sync.service.spec.ts b/src/procon/aggregate/procon-sync.service.spec.ts index 426d8a9..792f6bc 100644 --- a/src/procon/aggregate/procon-sync.service.spec.ts +++ b/src/procon/aggregate/procon-sync.service.spec.ts @@ -96,6 +96,31 @@ describe('Einzelsynchronisierung', () => { jest.spyOn(service, 'compareGroup').mockResolvedValue({ version: 'after' } as any); return id; } + it('ordnet neue Pfeile dem vorhandenen Aggregat zu und erhält editierbare Punkte nach dem Laden', async () => { + const id = group(); data.elements[0].key = 'main'; + const generator = { grafikTyp: 'pfeil' as const, config: { points: [{ x: 6, y: 6 }, { x: 86, y: 46 }] }, options: {} }; + await service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: id, + elements: [{ id, values }], newArrows: [{ key: 'pfeil_1', values: { ...values, x: 120, y: 80 }, generator }] }); + const stored = updates.updateOne.mock.calls[0][1].$set.elemente; + const reloaded = new View({ visuAggregateId: data.document.visuAggregateId, elemente: stored }); + await reloaded.validate(); + const arrow = reloaded.elemente.find(element => element.key === 'pfeil_1')!; + expect(arrow._id).toBeDefined(); expect(arrow.posX).toBe(120); expect(arrow.posY).toBe(80); + expect(arrow.darstellung).toBe('xaml'); + if (arrow.darstellung === 'xaml') { + expect(arrow.generator?.config.points).toEqual(generator.config.points); + expect(arrow.varianten[0].xamlBase64).toBe('PFZpZXdib3gvPg=='); + } + expect(reloaded.visuAggregateId.toString()).toBe(data.document.visuAggregateId.toString()); + }); + it('verhindert doppelte Pfeilschlüssel und fremde Generatoren beim Anlegen', async () => { + const id = group(); data.elements[0].key = 'pfeil_1'; + for (const grafikTyp of ['pfeil', 'motor'] as const) { + await expect(service.applyGroup(1, { version: 'reviewed', direction: 'saveLocal', masterId: id, + elements: [{ id, values }], newArrows: [{ key: 'pfeil_1', values, generator: { grafikTyp, config: {}, options: {} } }] })).rejects.toThrow('Pfeile'); + } + expect(updates.updateOne).not.toHaveBeenCalled(); + }); 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 }] }); diff --git a/src/procon/aggregate/procon-sync.service.ts b/src/procon/aggregate/procon-sync.service.ts index d873f54..4fd0efa 100644 --- a/src/procon/aggregate/procon-sync.service.ts +++ b/src/procon/aggregate/procon-sync.service.ts @@ -1,6 +1,6 @@ import { BadRequestException, Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; +import { Model, Types } from 'mongoose'; import * as sql from 'mssql'; import { createHash } from 'node:crypto'; import { Anlage } from '../../_schemas/anlage.schema'; @@ -32,6 +32,7 @@ export interface GroupSyncRequest { masterId: string; elementIds?: string[]; elements?: { id: string; values: GroupSyncValues; generator?: GrafikGeneratorDaten }[]; + newArrows?: { key: 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])) || @@ -116,6 +117,11 @@ export class ProConSyncService { 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 (dto.newArrows !== undefined && (!Array.isArray(dto.newArrows) || dto.newArrows.length > 100 || + dto.newArrows.some(item => !item || typeof item.key !== 'string' || !/^pfeil_[0-9]+$/.test(item.key) || item.generator?.grafikTyp !== 'pfeil') || + new Set([...data.elements.map(item => item.key), ...dto.newArrows.map(item => item.key)]).size !== data.elements.length + dto.newArrows.length)) + throw new BadRequestException('Neue Pfeile benötigen eindeutige Schlüssel und einen Pfeilgenerator'); + dto.newArrows?.forEach(item => validateGroupValues(item.values)); 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))) @@ -175,6 +181,17 @@ export class ProConSyncService { })); } } + if (dto.direction === 'saveLocal') for (const arrow of dto.newArrows ?? []) { + const { config, options } = arrow.generator; + const ergebnis = this.draw.renderGraphic('pfeil', { config, options }); + data.document.elemente.push({ + _id: new Types.ObjectId(), key: arrow.key, name: arrow.key, typ: 'pfeil', darstellung: 'xaml', + posX: arrow.values.x, posY: arrow.values.y, zIndex: arrow.values.z, show: arrow.values.show, + width: ergebnis.width, height: ergebnis.height, manuell: false, + generator: { grafikTyp: 'pfeil', config, options: options ?? {}, ergebnis }, + 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();