visualisierung

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

No files matched your search

@@ -0,0 +1,16 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="702" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="52" Height="702">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="681"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,-680 v 700 h 40 v -700 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,-680 v 700 h 30 v -700 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 0,0 v 20 h 50 v -20 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 12 h 42 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="20" Canvas.Top="345" Width="12" Height="12" StrokeThickness="1" Stroke="#00f000" Fill="#00f000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,16 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="702" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="52" Height="702">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="681"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,-680 v 700 h 40 v -700 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,-680 v 700 h 30 v -700 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 0,0 v 20 h 50 v -20 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 12 h 42 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="20" Canvas.Top="345" Width="12" Height="12" StrokeThickness="1" Stroke="#f00000" Fill="#f00000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="10" Height="50">
<Path Data="M 1,1 H 9 V 49 H 1 Z"
Stroke="#000000"
StrokeThickness="1"
Fill="Transparent"/>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#f00000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#f00000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#f00000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#f00000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="46" Height="562" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="46" Height="562">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,0 v 560 h 34 v -560 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,0 v 560 h 24 v -560 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 0,540 v 20 h 44 v -20 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,544 v 12 h 36 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 20 h 44 v -20 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 12 h 36 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="17.9" Canvas.Top="275.9" Width="10.2" Height="10.2" StrokeThickness="1" Stroke="#00f000" Fill="#00f000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="46" Height="562" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="46" Height="562">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,0 v 560 h 34 v -560 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,0 v 560 h 24 v -560 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 0,540 v 20 h 44 v -20 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,544 v 12 h 36 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 20 h 44 v -20 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 12 h 36 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="17.9" Canvas.Top="275.9" Width="10.2" Height="10.2" StrokeThickness="1" Stroke="#f00000" Fill="#f00000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="10" Height="50">
<Path Data="M 0,0 H 9 V 9 H 1 Z"
Stroke="#000000"
StrokeThickness="1"
Fill="Transparent"/>
<Canvas.RenderTransform>
<TranslateTransform X="0.5" Y="0.5"/>
</Canvas.RenderTransform>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#f00000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="202" Height="52" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="202" Height="52">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 0,5 v 40 h 200 v -40 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 0,8 v 34 h 200 v -34 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 180,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 184,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="95" Canvas.Top="20" Width="12" Height="12" StrokeThickness="1" Stroke="#00f000" Fill="#00f000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="202" Height="52" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="202" Height="52">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 0,5 v 40 h 200 v -40 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 0,8 v 34 h 200 v -34 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 180,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 184,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="95" Canvas.Top="20" Width="12" Height="12" StrokeThickness="1" Stroke="#f00000" Fill="#f00000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,17 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="202" Height="52" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="202" Height="52">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 0,5 v 40 h 200 v -40 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 0,8 v 34 h 200 v -34 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 180,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 184,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="202" Height="52" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="202" Height="52">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 0,5 v 40 h 200 v -40 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 0,8 v 34 h 200 v -34 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 180,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 184,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="95" Canvas.Top="20" Width="12" Height="12" StrokeThickness="1" Stroke="#00f000" Fill="#00f000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,18 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="202" Height="52" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="202" Height="52">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 0,5 v 40 h 200 v -40 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 0,8 v 34 h 200 v -34 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 180,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 184,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
<Ellipse Canvas.Left="95" Canvas.Top="20" Width="12" Height="12" StrokeThickness="1" Stroke="#f00000" Fill="#f00000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,17 @@
<?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="202" Height="52" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="202" Height="52">
<Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="1"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 0,5 v 40 h 200 v -40 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 0,8 v 34 h 200 v -34 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path>
<Path Data="M 180,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 184,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
<Path Data="M 0,0 v 50 h 20 v -50 Z" StrokeThickness="2" Stroke="#101010" Fill="#e0e0e0" ></Path>
<Path Data="M 4,4 v 42 h 12 v -42 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Stretch="Uniform" Width="20" Height="20"><Canvas Width="8.5996358" Height="8.0163929"><Canvas><Canvas.RenderTransform><TranslateTransform X="-416.06522" Y="-311.46089"/></Canvas.RenderTransform><Path Fill="#FAC44F" StrokeThickness="0.352777"><Path.Data><PathGeometry Figures="m 424.39268 319.47728 h -8.05519 c -0.36301 -0.36301 -0.36301 -0.95151 -1.1e-4 -1.31452 l 3.47998 -6.42969 c 0.3629 -0.36291 0.95141 -0.36291 1.31442 0 l 3.2609 6.42979 c 0.3629 0.36291 0.3629 0.95141 0 1.31442 z m -4.80212 -5.80912 0.38721 3.17549 h 0.77442 l 0.38728 -3.17549 z m 0.77442 3.64031 c -0.34209 0 -0.61958 0.27739 -0.61958 0.61958 0 0.3422 0.27749 0.61962 0.61958 0.61962 0.34219 0 0.61958 -0.27742 0.61958 -0.61962 0 -0.34219 -0.27739 -0.61958 -0.61958 -0.61958" FillRule="EvenOdd"/></Path.Data></Path></Canvas></Canvas></Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#f00000" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0" Canvas.Top="0" Width="24" Height="24" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
<Grid Canvas.Left="0" Canvas.Top="0" Width="24" Height="24"><TextBlock Text="M" FontFamily="Arial" FontSize="14.399999999999999" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Viewbox>
+8 -2
View File
@@ -7,21 +7,27 @@ export class BandObenRenderDto {
} }
export function parseBandObenRequest(input: unknown): BandObenRenderDto { export function parseBandObenRequest(input: unknown): BandObenRenderDto {
const object = (value: unknown): value is Record<string, unknown> => const object = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);
typeof value === 'object' && value !== null && !Array.isArray(value);
if (!object(input) || Object.keys(input).some(key => !['config', 'options'].includes(key)) || !object(input.config)) if (!object(input) || Object.keys(input).some(key => !['config', 'options'].includes(key)) || !object(input.config))
throw new BadRequestException('Erwartet werden config und optional options'); throw new BadRequestException('Erwartet werden config und optional options');
const config = input.config; const config = input.config;
if (Object.keys(config).some(key => !['width', 'length'].includes(key)) || if (Object.keys(config).some(key => !['width', 'length'].includes(key)) ||
typeof config.width !== 'number' || !Number.isFinite(config.width) || config.width <= 10 || typeof config.width !== 'number' || !Number.isFinite(config.width) || config.width <= 10 ||
typeof config.length !== 'number' || !Number.isFinite(config.length) || config.length <= 0) typeof config.length !== 'number' || !Number.isFinite(config.length) || config.length <= 0)
throw new BadRequestException('config.width muss größer als 10 und config.length positiv sein; beide Werte müssen endliche Zahlen sein'); throw new BadRequestException('config.width muss größer als 10 und config.length positiv sein; beide Werte müssen endliche Zahlen sein');
const options = input.options === undefined ? {} : input.options; const options = input.options === undefined ? {} : input.options;
if (!object(options) || Object.entries(options).some(([key, value]) => if (!object(options) || Object.entries(options).some(([key, value]) =>
!['fromNorthToSouth', 'trichterStart', 'trichterEnd'].includes(key) || typeof value !== 'boolean')) !['fromNorthToSouth', 'trichterStart', 'trichterEnd'].includes(key) || typeof value !== 'boolean'))
throw new BadRequestException('options erlaubt nur fromNorthToSouth, trichterStart und trichterEnd als Boolean'); throw new BadRequestException('options erlaubt nur fromNorthToSouth, trichterStart und trichterEnd als Boolean');
if ((options.trichterStart || options.trichterEnd) && config.length < 20) if ((options.trichterStart || options.trichterEnd) && config.length < 20)
throw new BadRequestException('Mit Trichter muss die Bandlänge mindestens 20 sein'); throw new BadRequestException('Mit Trichter muss die Bandlänge mindestens 20 sein');
return { return {
config: { width: config.width, length: config.length }, config: { width: config.width, length: config.length },
options: { options: {
+1 -2
View File
@@ -27,8 +27,7 @@ export class DrawDataDto {
name!:string; name!:string;
height!: number; height!: number;
width!:number; width!:number;
svg!:{state:string,data:string}[] varianten!: { state: 'inactive' | 'active' | 'error'; svg: string; xaml: string; xamlBase64: string }[];
xaml!:{state:"inactive" | "active" | "error",data:string,base64?:string}[]
} }
export class DrawShapeOptionenDto{ export class DrawShapeOptionenDto{
+42
View File
@@ -0,0 +1,42 @@
import { BadRequestException } from '@nestjs/common';
import type { MotorConfig, MotorOptions } from '../graphics/elements/types';
export class MotorRenderDto {
config!: MotorConfig;
options?: Partial<MotorOptions>;
}
export function parseMotorRequest(input: unknown): MotorRenderDto {
const object = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !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 config = input.config;
if (Object.keys(config).some(key => !['scale', 'raster'].includes(key)))
throw new BadRequestException('Motor-config erlaubt nur scale und raster');
const scale = config.scale ?? 2, raster = config.raster ?? 4;
if (typeof scale !== 'number' ||
!Number.isFinite(scale) ||
scale <= 0 ||
typeof raster !== 'number' ||
!Number.isFinite(raster) ||
raster <= 0 ||
!Number.isFinite(3 * scale * raster)
)
throw new BadRequestException('scale und raster müssen positive endliche Zahlen sein');
const options = input.options === undefined ? {} : 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('Motor-options erlaubt colorInactive, colorActive und colorError als Hexfarbe #RRGGBB');
return { config: { scale, raster }, options: options as Partial<MotorOptions> };
}
+39
View File
@@ -0,0 +1,39 @@
import { BadRequestException } from '@nestjs/common';
import { Types } from 'mongoose';
import type { ProConVerbindung } from '../_schemas/procon-verbindung';
export class ProConVerbindungenDto {
verbindungen!: (Omit<ProConVerbindung, '_id'> & { id?: string })[];
aktiveVerbindungId!: string | null;
}
export function parseVerbindungen(input: ProConVerbindungenDto) {
if (!input || !Array.isArray(input.verbindungen)) throw new BadRequestException('Verbindungsliste fehlt');
const ids = new Set<string>();
const verbindungen = input.verbindungen.map(item => {
if (!item || ['name', 'server', 'datenbank', 'benutzer'].some(key => typeof item[key] !== 'string' || !item[key].trim()) ||
typeof item.passwort !== 'string' || typeof item.instanz !== 'string' ||
!['test', 'produktion'].includes(item.umgebung) ||
typeof item.encrypt !== 'boolean' || typeof item.trustServerCertificate !== 'boolean')
throw new BadRequestException('Verbindungsdaten sind unvollständig');
if (item.server.includes('\\') || item.server.includes('/') || (item.instanz && item.port !== null))
throw new BadRequestException('Server und Instanz getrennt eingeben; entweder Instanz oder Port verwenden');
if ((item.port !== null && (!Number.isInteger(item.port) || item.port < 1 || item.port > 65535)) ||
!Number.isInteger(item.connectionTimeoutMs) || item.connectionTimeoutMs < 1000 || item.connectionTimeoutMs > 60000)
throw new BadRequestException('Port muss 1–65535 und Timeout 1000–60000 ms betragen');
if (item.id && !Types.ObjectId.isValid(item.id)) throw new BadRequestException('Ungültige Verbindungs-ID');
const _id = item.id ? new Types.ObjectId(item.id) : new Types.ObjectId();
if (ids.has(_id.toString())) throw new BadRequestException('Doppelte Verbindungs-ID');
ids.add(_id.toString());
return {
_id, name: item.name.trim(), server: item.server.trim(), instanz: item.instanz.trim(),
port: item.port, datenbank: item.datenbank.trim(), benutzer: item.benutzer.trim(),
passwort: item.passwort, umgebung: item.umgebung, encrypt: item.encrypt,
trustServerCertificate: item.trustServerCertificate, connectionTimeoutMs: item.connectionTimeoutMs,
};
});
if (input.aktiveVerbindungId !== null && !ids.has(input.aktiveVerbindungId))
throw new BadRequestException('Aktive Verbindung ist nicht in der Liste enthalten');
return { verbindungen, aktiveVerbindungId: input.aktiveVerbindungId };
}
+7
View File
@@ -1,5 +1,7 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose'; import { Document } from 'mongoose';
import { ProConVerbindungSchema } from './procon-verbindung';
import type { ProConVerbindung } from './procon-verbindung';
interface AnlageJSON { interface AnlageJSON {
id: string; id: string;
@@ -9,6 +11,11 @@ interface AnlageJSON {
@Schema() @Schema()
export class Anlage extends Document { export class Anlage extends Document {
@Prop({ type: [ProConVerbindungSchema], default: [] })
proConVerbindungen!: ProConVerbindung[];
@Prop({ type: String, default: null })
aktiveProConVerbindungId!: string | null;
@Prop() @Prop()
@@ -27,7 +27,7 @@ describe('ProConViewAggregate', () => {
{ ...basis, darstellung: 'xaml', typ: 'main', varianten: [ { ...basis, darstellung: 'xaml', typ: 'main', varianten: [
{ zustand: 'active', xamlBase64: '' }, { zustand: 'inactive' }, { zustand: 'active', xamlBase64: '' }, { zustand: 'inactive' },
] }, ] },
{ ...basis, key: 'motor', darstellung: 'xaml', typ: 'motor' }, { ...basis, key: 'motor', darstellung: 'xaml', typ: 'main' },
]); ]);
await document.validate(); await document.validate();
expect(document.toObject().elemente[0]).toEqual(expect.objectContaining({ expect(document.toObject().elemente[0]).toEqual(expect.objectContaining({
@@ -36,7 +36,7 @@ describe('ProConViewAggregate', () => {
expect(document.toObject().elemente[1]).toEqual(expect.objectContaining({ varianten: [] })); expect(document.toObject().elemente[1]).toEqual(expect.objectContaining({ varianten: [] }));
}); });
it.each(['anfahrzeit', 'betriebsart', 'text'])('speichert %s ohne XAML-Felder', async typ => { it.each(['anfahrzeit', 'betriebsart', 'text', 'motor'])('speichert %s ohne XAML-Felder', async typ => {
const document = create([{ ...basis, darstellung: 'standard', typ }]); const document = create([{ ...basis, darstellung: 'standard', typ }]);
await document.validate(); await document.validate();
expect(document.toObject().elemente[0]).not.toHaveProperty('varianten'); expect(document.toObject().elemente[0]).not.toHaveProperty('varianten');
+34 -8
View File
@@ -1,9 +1,19 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, Schema as MongooseSchema, Types } from 'mongoose'; import { HydratedDocument, Schema as MongooseSchema, Types } from 'mongoose';
import { VisuAggregate } from './visu-aggregate'; import { VisuAggregate } from './visu-aggregate';
import type { DrawDataDto } from '../../_dto/draw.dto';
export interface GrafikGeneratorDaten {
grafikTyp: 'motor' | 'bandOben' | 'warnung';
config: Record<string, unknown>;
options: Record<string, unknown>;
ergebnis?: DrawDataDto;
}
export interface XamlVariante { export interface XamlVariante {
zustand: string; zustand: string;
svg?: string;
xaml?: string;
xamlBase64: string; xamlBase64: string;
} }
@@ -17,20 +27,23 @@ export interface ViewElementBasis {
posY: number; posY: number;
zIndex: number; zIndex: number;
show: boolean; show: boolean;
manuell?: boolean;
} }
export type ProConViewElement = export type ProConViewElement =
| (ViewElementBasis & { darstellung: 'xaml'; typ: string; varianten: XamlVariante[] }) | (ViewElementBasis & { darstellung: 'xaml'; typ: string; varianten: XamlVariante[]; generator?: GrafikGeneratorDaten })
| (ViewElementBasis & { darstellung: 'standard'; typ: 'anfahrzeit' | 'betriebsart' | 'text' }); | (ViewElementBasis & { darstellung: 'standard'; typ: 'anfahrzeit' | 'betriebsart' | 'text' | 'motor' });
const standardTypen = ['anfahrzeit', 'betriebsart', 'text']; const standardTypen = ['anfahrzeit', 'betriebsart', 'text', 'motor'];
const dateiTeil = /^[a-zA-Z0-9_-]+$/; const dateiTeil = /^[a-zA-Z0-9_-]+$/;
const endlich = { validator: Number.isFinite, message: 'Wert muss eine endliche Zahl sein' }; const endlich = { validator: Number.isFinite, message: 'Wert muss eine endliche Zahl sein' };
const VarianteSchema = new MongooseSchema<XamlVariante>({ const VarianteSchema = new MongooseSchema<XamlVariante>({
svg: { type: String },
xaml: { type: String },
zustand: { type: String, required: true, match: dateiTeil }, zustand: { type: String, required: true, match: dateiTeil },
xamlBase64: { type: String, default: '' }, xamlBase64: { type: String, default: '' },
}, { _id: false, strict: 'throw' }); }, { _id: false, strict: 'throw', minimize: false });
const ElementSchema = new MongooseSchema<ViewElementBasis>({ const ElementSchema = new MongooseSchema<ViewElementBasis>({
key: { type: String, required: true, match: dateiTeil }, key: { type: String, required: true, match: dateiTeil },
@@ -41,12 +54,16 @@ const ElementSchema = new MongooseSchema<ViewElementBasis>({
posY: { type: Number, required: true, validate: endlich }, posY: { type: Number, required: true, validate: endlich },
zIndex: { type: Number, required: true, validate: { validator: Number.isSafeInteger, message: 'zIndex muss ganzzahlig sein' } }, zIndex: { type: Number, required: true, validate: { validator: Number.isSafeInteger, message: 'zIndex muss ganzzahlig sein' } },
show: { type: Boolean, default: true }, show: { type: Boolean, default: true },
}, { discriminatorKey: 'darstellung', strict: 'throw' }); manuell: { type: Boolean, default: false },
}, { discriminatorKey: 'darstellung', strict: 'throw', minimize: false });
@Schema({ collection: 'proConViewAggregate', timestamps: true, strict: 'throw' }) @Schema({ collection: 'proConViewAggregate', timestamps: true, strict: 'throw', minimize: false })
export class ProConViewAggregate { export class ProConViewAggregate {
_id!: Types.ObjectId; _id!: Types.ObjectId;
@Prop({ type: String, default: null })
positionsMasterId!: string | null;
@Prop({ type: MongooseSchema.Types.ObjectId, ref: VisuAggregate.name, required: true, immutable: true }) @Prop({ type: MongooseSchema.Types.ObjectId, ref: VisuAggregate.name, required: true, immutable: true })
visuAggregateId!: Types.ObjectId; visuAggregateId!: Types.ObjectId;
@@ -69,6 +86,15 @@ ProConViewAggregateSchema.index({ visuAggregateId: 1 }, { unique: true });
const elemente = ProConViewAggregateSchema.path<MongooseSchema.Types.DocumentArray>('elemente'); const elemente = ProConViewAggregateSchema.path<MongooseSchema.Types.DocumentArray>('elemente');
elemente.discriminator('xaml', new MongooseSchema({ elemente.discriminator('xaml', new MongooseSchema({
generator: {
type: new MongooseSchema({
grafikTyp: { type: String, enum: ['motor', 'bandOben', 'warnung'], required: true },
config: { type: MongooseSchema.Types.Mixed, required: true },
options: { type: MongooseSchema.Types.Mixed, default: () => ({}) },
ergebnis: { type: MongooseSchema.Types.Mixed },
}, { _id: false, strict: 'throw', minimize: false }),
default: undefined,
},
typ: { typ: {
type: String, required: true, type: String, required: true,
validate: { validator: (typ: string) => !standardTypen.includes(typ), message: 'Dieser Elementtyp verwendet keine XAML-Grafiken' }, validate: { validator: (typ: string) => !standardTypen.includes(typ), message: 'Dieser Elementtyp verwendet keine XAML-Grafiken' },
@@ -80,8 +106,8 @@ elemente.discriminator('xaml', new MongooseSchema({
message: 'Zustände müssen pro Element eindeutig sein', message: 'Zustände müssen pro Element eindeutig sein',
}, },
}, },
}, { _id: false, strict: 'throw' })); }, { _id: false, strict: 'throw', minimize: false }));
elemente.discriminator('standard', new MongooseSchema({ elemente.discriminator('standard', new MongooseSchema({
typ: { type: String, enum: standardTypen, required: true }, typ: { type: String, enum: standardTypen, required: true },
}, { _id: false, strict: 'throw' })); }, { _id: false, strict: 'throw', minimize: false }));
+19
View File
@@ -0,0 +1,19 @@
import { Schema, Types } from 'mongoose';
export interface ProConZuordnung {
anlageId: string;
verbindungId: string;
proConAggregateId: number;
spsAntriebId: number;
visuAggregateId: Types.ObjectId;
elemente: { visualizationId: number; elementId: string; key: string }[];
}
export const ProConZuordnungSchema = new Schema<ProConZuordnung>({
anlageId: { type: String, required: true },
verbindungId: { type: String, required: true },
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: [] },
}, { 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 });
@@ -0,0 +1,12 @@
import { Schema } from 'mongoose';
import type { VisualisierungSettingsDto } from '../../visualisierung/visualisierung.dto';
export interface VisualisierungSettings extends VisualisierungSettingsDto { anlageId: string }
export const VisualisierungSettingsSchema = new Schema<VisualisierungSettings>({
anlageId: { type: String, required: true, unique: true },
workspaceWidth: { type: Number, required: true }, workspaceHeight: { type: Number, required: true },
grid: { type: Boolean, required: true }, gridStep: { type: Number, required: true },
snapToGrid: { type: Boolean, required: true }, showHidden: { type: Boolean, required: true },
selectedSpsAntriebId: { type: Number, default: null },
viewport: { type: new Schema({ x: Number, y: Number, width: Number, height: Number }, { _id: false }), required: true },
}, { collection: 'visualisierung_settings', timestamps: true, strict: 'throw' });
+31
View File
@@ -0,0 +1,31 @@
import { Schema, Types } from 'mongoose';
export interface ProConVerbindung {
_id: Types.ObjectId;
name: string;
umgebung: 'test' | 'produktion';
server: string;
instanz: string;
port: number | null;
datenbank: string;
benutzer: string;
passwort: string;
encrypt: boolean;
trustServerCertificate: boolean;
connectionTimeoutMs: number;
}
export const ProConVerbindungSchema = new Schema<ProConVerbindung>({
name: { type: String, required: true },
umgebung: { type: String, enum: ['test', 'produktion'], required: true },
server: { type: String, required: true },
instanz: { type: String, default: '' },
port: { type: Number, default: null },
datenbank: { type: String, required: true },
benutzer: { type: String, required: true },
passwort: { type: String, default: '' },
encrypt: { type: Boolean, default: true },
trustServerCertificate: { type: Boolean, default: false },
connectionTimeoutMs: { type: Number, default: 3000 },
});
@@ -1,4 +1,5 @@
import { Body, Controller, Get, Param, Put } from '@nestjs/common'; import { Body, Controller, Get, Param, Post, Put, HttpCode } from '@nestjs/common';
import { XamlExportDto } from './procon-xaml-export';
import { ProConViewAggregateUpdateDto } from '../../_dto/anlagen/procon-view-aggregate'; import { ProConViewAggregateUpdateDto } from '../../_dto/anlagen/procon-view-aggregate';
import { ProConViewAggregateService } from './procon-view-aggregate.service'; import { ProConViewAggregateService } from './procon-view-aggregate.service';
@@ -7,6 +8,9 @@ export class ProConViewAggregateController {
constructor(private readonly service: ProConViewAggregateService) {} constructor(private readonly service: ProConViewAggregateService) {}
@Get() @Get()
findAll() { return this.service.findAll(); } findAll() { return this.service.findAll(); }
@Post('xaml')
@HttpCode(200)
exportXaml(@Body() dto: XamlExportDto) { return this.service.exportXaml(dto); }
@Get(':componentId') @Get(':componentId')
findOne(@Param('componentId') id: string) { return this.service.findOne(id); } findOne(@Param('componentId') id: string) { return this.service.findOne(id); }
@Put(':componentId') @Put(':componentId')
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals'; import { beforeEach, describe, expect, it, jest } from '@jest/globals';
jest.mock('../../rk-anlagen/anlage/anlage.service', () => ({ AnlageService: class AnlageService {} })); jest.mock('../../rk-anlagen/anlage/anlage.service', () => ({ AnlageService: class AnlageService {} }));
jest.mock('../../draw/draw.service', () => ({ DrawService: class DrawService {} }));
import { model, Types } from 'mongoose'; import { model, Types } from 'mongoose';
import { ProConViewAggregateSchema } from '../../_schemas/anlagen/procon-view-aggregate'; import { ProConViewAggregateSchema } from '../../_schemas/anlagen/procon-view-aggregate';
import { ProConViewAggregateService } from './procon-view-aggregate.service'; import { ProConViewAggregateService } from './procon-view-aggregate.service';
@@ -22,7 +23,7 @@ describe('ProConViewAggregateService', () => {
lean: () => ({ exec: async () => null }), lean: () => ({ exec: async () => null }),
})); }));
aggregates = { findOne: jest.fn(() => ({ exec: async () => aggregate })) }; aggregates = { findOne: jest.fn(() => ({ exec: async () => aggregate })) };
service = new ProConViewAggregateService(views, aggregates, { getSelected: async () => ({ id: anlageId }) } as any); service = new ProConViewAggregateService(views, aggregates, { getSelected: async () => ({ id: anlageId }) } as any, {} as any);
}); });
it('liefert für noch nicht angelegte Grafiken eine leere Elementliste', async () => { it('liefert für noch nicht angelegte Grafiken eine leere Elementliste', async () => {
@@ -72,6 +73,27 @@ describe('ProConViewAggregateService', () => {
expect(views).not.toHaveBeenCalled(); expect(views).not.toHaveBeenCalled();
}); });
it('erzeugt und speichert das vollständige Generatorergebnis anstelle veralteter Daten', async () => {
const ergebnis = {
name: 'motor', width: 24, height: 24,
varianten: [{ state: 'active', svg: '<svg/>', xaml: '<Viewbox/>', xamlBase64: Buffer.from('<Viewbox/>').toString('base64') }],
};
const renderGraphic = jest.fn(() => ergebnis);
service = new ProConViewAggregateService(views, aggregates, { getSelected: async () => ({ id: anlageId }) } as any, { renderGraphic } as any);
await service.save(componentId, { anlageId, elemente: [{
key: 'motor', name: '', darstellung: 'xaml', typ: 'main',
width: 1, height: 1, posX: 100, posY: 200, zIndex: 3, show: true, varianten: [],
generator: { grafikTyp: 'motor', config: { scale: 2, raster: 4 }, options: {} },
}] });
expect(renderGraphic).toHaveBeenCalledWith('motor', { config: { scale: 2, raster: 4 }, options: {} });
const document = views.mock.results[0].value;
expect(document.toObject().elemente[0]).toEqual(expect.objectContaining({
width: 24, height: 24, posX: 100, posY: 200,
generator: { grafikTyp: 'motor', config: { scale: 2, raster: 4 }, options: {}, ergebnis },
varianten: [{ zustand: 'active', svg: '<svg/>', xaml: '<Viewbox/>', xamlBase64: Buffer.from('<Viewbox/>').toString('base64') }],
}));
});
it('meldet ungültige Elemente als Eingabefehler', async () => { it('meldet ungültige Elemente als Eingabefehler', async () => {
await expect(service.save(componentId, { anlageId, elemente: [{ key: 'leer' } as any] })).rejects.toMatchObject({ status: 400 }); await expect(service.save(componentId, { anlageId, elemente: [{ key: 'leer' } as any] })).rejects.toMatchObject({ status: 400 });
}); });
@@ -5,6 +5,21 @@ import { ProConViewAggregate } from '../../_schemas/anlagen/procon-view-aggregat
import { VisuAggregate } from '../../_schemas/anlagen/visu-aggregate'; import { VisuAggregate } from '../../_schemas/anlagen/visu-aggregate';
import { AnlageService } from '../../rk-anlagen/anlage/anlage.service'; import { AnlageService } from '../../rk-anlagen/anlage/anlage.service';
import { ProConViewAggregateUpdateDto } from '../../_dto/anlagen/procon-view-aggregate'; import { ProConViewAggregateUpdateDto } from '../../_dto/anlagen/procon-view-aggregate';
import { DrawService } from '../../draw/draw.service';
import type { ProConViewElement } from '../../_schemas/anlagen/procon-view-aggregate';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { createXamlFiles, XamlExportDto } from './procon-xaml-export';
function normalizeMotor(element: ProConViewElement): ProConViewElement {
if (element.typ !== 'motor') return element;
return {
_id: element._id, key: element.key, name: element.name, typ: 'motor', darstellung: 'standard',
width: element.width, height: element.height, posX: element.posX, posY: element.posY,
zIndex: element.zIndex, show: element.show,
manuell: element.manuell,
};
}
@Injectable() @Injectable()
export class ProConViewAggregateService { export class ProConViewAggregateService {
@@ -12,8 +27,33 @@ export class ProConViewAggregateService {
@InjectModel(ProConViewAggregate.name, 'anlagen') private readonly views: Model<ProConViewAggregate>, @InjectModel(ProConViewAggregate.name, 'anlagen') private readonly views: Model<ProConViewAggregate>,
@InjectModel(VisuAggregate.name, 'anlagen') private readonly aggregates: Model<VisuAggregate>, @InjectModel(VisuAggregate.name, 'anlagen') private readonly aggregates: Model<VisuAggregate>,
private readonly anlagen: AnlageService, private readonly anlagen: AnlageService,
private readonly draw: DrawService,
) {} ) {}
async exportXaml(dto: XamlExportDto) {
const anlage = await this.anlagen.getSelected();
const anlageId = anlage.id;
if (!dto || dto.anlageId !== anlageId) throw new BadRequestException('Anlage hat sich geändert. Bitte neu laden.');
if (!Array.isArray(dto.auswahl) || dto.auswahl.length === 0 || dto.auswahl.some(item =>
!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();
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()
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_')
.replace(/[ .]+$/g, '');
if (!safeName || !Number.isSafeInteger(anlage.anlageNr))
throw new BadRequestException('Anlagennummer oder Anlagenname ist ungültig');
const folder = anlage.anlageNr + '_' + safeName;
const target = resolve(process.cwd(), 'data', folder, 'xaml');
if (files.length) {
await mkdir(target, { recursive: true });
for (const file of files) await writeFile(join(target, file.name), file.data, 'utf8');
}
return { count: files.length, skipped, directory: 'data/' + folder + '/xaml' };
}
async findAll() { async findAll() {
const anlageId = (await this.anlagen.getSelected()).id; const anlageId = (await this.anlagen.getSelected()).id;
const aggregates = await this.aggregates.find({ const aggregates = await this.aggregates.find({
@@ -25,7 +65,7 @@ export class ProConViewAggregateService {
antriebId: aggregate.antriebId, antriebId: aggregate.antriebId,
name: aggregate.antriebName, name: aggregate.antriebName,
viewName: aggregate.view ?? '', viewName: aggregate.view ?? '',
elemente: views.find(view => view.visuAggregateId.toString() === aggregate._id.toString())?.elemente ?? [], elemente: (views.find(view => view.visuAggregateId.toString() === aggregate._id.toString())?.elemente ?? []).map(normalizeMotor),
})).sort((a, b) => a.antriebId - b.antriebId); })).sort((a, b) => a.antriebId - b.antriebId);
} }
@@ -49,7 +89,7 @@ export class ProConViewAggregateService {
anlageId, visuAggregateId: aggregate._id.toString(), anlageId, visuAggregateId: aggregate._id.toString(),
viewName: aggregate.view ?? '', name: aggregate.antriebName, viewName: aggregate.view ?? '', name: aggregate.antriebName,
anzahlMotoren: aggregate.anzahlMotoren ?? 1, anzahlMotoren: aggregate.anzahlMotoren ?? 1,
persisted: !!view, elemente: view?.elemente ?? [], persisted: !!view, elemente: (view?.elemente ?? []).map(normalizeMotor),
}; };
} }
@@ -57,10 +97,24 @@ export class ProConViewAggregateService {
const { aggregate, anlageId } = await this.parent(componentId); const { aggregate, anlageId } = await this.parent(componentId);
if (!dto || dto.anlageId !== anlageId) throw new BadRequestException('Die Anlage hat sich geändert. Bitte neu laden.'); if (!dto || dto.anlageId !== anlageId) throw new BadRequestException('Die Anlage hat sich geändert. Bitte neu laden.');
if (!Array.isArray(dto.elemente)) throw new BadRequestException('Elementliste fehlt'); if (!Array.isArray(dto.elemente)) throw new BadRequestException('Elementliste fehlt');
const elemente = dto.elemente.map(normalizeMotor).map(element => {
if (element?.darstellung !== 'xaml' || !element.generator || element.manuell) return element;
const { grafikTyp, config, options } = element.generator;
// Vor jedem Speichern serverseitig neu erzeugen: Parameter und Ergebnis bleiben konsistent.
const ergebnis = this.draw.renderGraphic(grafikTyp, { config, options });
return {
...element, width: ergebnis.width, height: ergebnis.height,
generator: { grafikTyp, config, options: options ?? {}, ergebnis },
varianten: ergebnis.varianten.map(variant => ({
zustand: variant.state,
svg: variant.svg, xaml: variant.xaml, xamlBase64: variant.xamlBase64,
})),
};
});
try { try {
const document = await this.views.findOne({ visuAggregateId: aggregate._id }).exec() const document = await this.views.findOne({ visuAggregateId: aggregate._id }).exec()
?? new this.views({ visuAggregateId: aggregate._id }); ?? new this.views({ visuAggregateId: aggregate._id });
document.set('elemente', dto.elemente); document.set('elemente', elemente);
await document.save(); await document.save();
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
@@ -0,0 +1,38 @@
import { describe, expect, it } from '@jest/globals';
import { createXamlFiles } from './procon-xaml-export';
import type { ProConViewElement } from '../../_schemas/anlagen/procon-view-aggregate';
describe('XAML-Dateiexport', () => {
const element: ProConViewElement = {
key: 'main', name: '', darstellung: 'xaml', typ: 'main',
width: 40, height: 40, posX: 0, posY: 0, zIndex: 0, show: true,
varianten: [
{ zustand: 'active', xaml: '<Viewbox>ä</Viewbox>', xamlBase64: '' },
{ zustand: 'inactive', xamlBase64: Buffer.from('<Viewbox/>').toString('base64') },
{ zustand: 'error', xamlBase64: '' },
],
};
const aggregates = [{ componentId: 'c1', viewName: 'SF1_Band', elemente: [element] }];
const dto = { anlageId: 'a1', auswahl: [{ componentId: 'c1', elementKeys: ['main'] }] };
it('erstellt Dateien für die Auswahl und dekodiert ältere Base64-Daten', () => {
expect(createXamlFiles(aggregates, dto)).toEqual({
files: [
{ name: 'SF1_Band_main_active.xaml', data: '<Viewbox>ä</Viewbox>' },
{ name: 'SF1_Band_main_inactive.xaml', data: '<Viewbox/>' },
], skipped: 1,
});
expect(createXamlFiles(aggregates, { ...dto, auswahl: [{ componentId: 'c1', elementKeys: [] }] }).files).toEqual([]);
});
it('verhindert Pfade außerhalb des Exportordners und leere View-Namen', () => {
for (const viewName of ['../fremd', 'C:\\fremd', '', 'Datei.']) {
expect(() => createXamlFiles([{ ...aggregates[0], viewName }], dto)).toThrow('Dateinamenbestandteile');
}
});
it('verhindert doppelte Dateinamen und unbekannte Auswahlen', () => {
expect(() => createXamlFiles(aggregates, { ...dto, auswahl: [...dto.auswahl, ...dto.auswahl] })).toThrow('Doppelter');
expect(() => createXamlFiles(aggregates, { ...dto, auswahl: [{ componentId: 'fremd', elementKeys: ['main'] }] })).toThrow('dieser Anlage');
});
});
@@ -0,0 +1,32 @@
import { BadRequestException } from '@nestjs/common';
import type { ProConViewElement } from '../../_schemas/anlagen/procon-view-aggregate';
export class XamlExportDto {
anlageId!: string;
auswahl!: { componentId: string; elementKeys: string[] }[];
}
export function createXamlFiles(aggregates: { componentId: string; viewName: string; elemente: ProConViewElement[] }[], dto: XamlExportDto) {
const files = new Map<string, { name: string; data: string }>();
let skipped = 0;
const safe = (value: string) => !!value && /^[\p{L}\p{N}_ .-]+$/u.test(value) && !value.includes('..') && !/[ .]$/.test(value);
for (const selection of dto.auswahl) {
const aggregate = aggregates.find(item => item.componentId === selection.componentId);
if (!aggregate) throw new BadRequestException('Ausgewähltes Aggregat ist in dieser Anlage nicht vorhanden');
for (const key of selection.elementKeys) {
const element = aggregate.elemente.find(item => item.key === key);
if (!element) throw new BadRequestException('Ausgewähltes Element ist nicht mehr vorhanden: ' + key);
if (element.darstellung !== 'xaml') continue;
for (const variant of element.varianten) {
const data = variant.xaml || (variant.xamlBase64 ? Buffer.from(variant.xamlBase64, 'base64').toString('utf8') : '');
if (!data.trim()) { skipped++; continue; }
if (![aggregate.viewName, element.key, variant.zustand].every(safe))
throw new BadRequestException('View, Element und Zustand müssen gültige Dateinamenbestandteile sein');
const name = aggregate.viewName + '_' + element.key + '_' + variant.zustand + '.xaml';
if (files.has(name.toLowerCase())) throw new BadRequestException('Doppelter Dateiname: ' + name);
files.set(name.toLowerCase(), { name, data });
}
}
}
return { files: [...files.values()], skipped };
}
@@ -8,9 +8,10 @@ import { VisuAggregateController } from './visu-aggregate.controller';
import { ProConViewAggregate, ProConViewAggregateSchema } from '../../_schemas/anlagen/procon-view-aggregate'; import { ProConViewAggregate, ProConViewAggregateSchema } from '../../_schemas/anlagen/procon-view-aggregate';
import { ProConViewAggregateService } from './procon-view-aggregate.service'; import { ProConViewAggregateService } from './procon-view-aggregate.service';
import { ProConViewAggregateController } from './procon-view-aggregate.controller'; import { ProConViewAggregateController } from './procon-view-aggregate.controller';
import { DrawModule } from '../../draw/draw.module';
@Module({ @Module({
imports: [AnlageModule, MongooseModule.forFeature([ imports: [AnlageModule, DrawModule, MongooseModule.forFeature([
{ name: VisuAggregate.name, schema: VisuAggregateSchema }, { name: VisuAggregate.name, schema: VisuAggregateSchema },
{ name: ProConViewAggregate.name, schema: ProConViewAggregateSchema }, { name: ProConViewAggregate.name, schema: ProConViewAggregateSchema },
{ name: Unit.name, schema: UnitSchema }, { name: Unit.name, schema: UnitSchema },
+2
View File
@@ -9,10 +9,12 @@ import { ProconModule } from './procon/procon.module';
import { SqlModule } from './infrastructure/sql/sql.module'; import { SqlModule } from './infrastructure/sql/sql.module';
import { FileWatcherModule } from './moon/file-watcher/file-watcher.module'; import { FileWatcherModule } from './moon/file-watcher/file-watcher.module';
import { AnlagenModule } from './anlagen/anlagen.module'; import { AnlagenModule } from './anlagen/anlagen.module';
import { VisualisierungModule } from './visualisierung/visualisierung.module';
@Module({ @Module({
imports: [ imports: [
VisualisierungModule,
MongooseModule.forRoot('mongodb://localhost/rk'), MongooseModule.forRoot('mongodb://localhost/rk'),
MongooseModule.forRoot('mongodb://localhost/rk2', { connectionName: 'anlagen' }), MongooseModule.forRoot('mongodb://localhost/rk2', { connectionName: 'anlagen' }),
UserModule, UserModule,
+3 -3
View File
@@ -17,10 +17,10 @@ const graphicMethods = {
export class DrawController { export class DrawController {
constructor(private readonly service: DrawService) {} constructor(private readonly service: DrawService) {}
@Post('bandOben/render') @Post(':grafikTyp/render')
@HttpCode(200) @HttpCode(200)
renderBandOben(@Body() body: unknown): DrawDataDto { renderGraphic(@Param('grafikTyp') grafikTyp: string, @Body() body: unknown): DrawDataDto {
return this.service.renderBandOben(body); return this.service.renderGraphic(grafikTyp, body);
} }
// Die Anlagenzeichnung ist kein einzelnes Grafiksymbol. // Die Anlagenzeichnung ist kein einzelnes Grafiksymbol.
+2
View File
@@ -22,11 +22,13 @@ import { DrawBehaelterMulti } from 'src/graphics/elements/drawBehaelterMulti';
import { DrawMotor } from 'src/graphics/elements/drawMotor'; import { DrawMotor } from 'src/graphics/elements/drawMotor';
import { DrawAnlageDurmin } from 'src/graphics/elements/drawAnlageDurmin2'; import { DrawAnlageDurmin } from 'src/graphics/elements/drawAnlageDurmin2';
import { DrawBandOben } from 'src/graphics/elements/drawBandOben'; import { DrawBandOben } from 'src/graphics/elements/drawBandOben';
import { DrawWarnung } from '../graphics/elements/drawWarnung';
@Module({ @Module({
imports: [], imports: [],
controllers: [DrawController], controllers: [DrawController],
providers: [ providers: [
DrawWarnung,
DrawService, DrawService,
Sieb, Sieb,
DrawGurtfoerderer, DrawGurtfoerderer,
+19 -1
View File
@@ -1,4 +1,6 @@
import { Injectable } from '@nestjs/common'; import { Injectable, NotFoundException } from '@nestjs/common';
import { parseMotorRequest } from '../_dto/motor.dto';
import { DrawWarnung, parseWarnungRequest } from '../graphics/elements/drawWarnung';
import { DrawShapeOptionenDto } from 'src/_dto/draw.dto'; import { DrawShapeOptionenDto } from 'src/_dto/draw.dto';
import { DrawBand } from 'src/graphics/elements/drawBand'; import { DrawBand } from 'src/graphics/elements/drawBand';
import { DrawBehaelter } from 'src/graphics/elements/drawBehaelter'; import { DrawBehaelter } from 'src/graphics/elements/drawBehaelter';
@@ -28,6 +30,7 @@ import { parseBandObenRequest } from '../_dto/band-oben.dto';
@Injectable() @Injectable()
export class DrawService { export class DrawService {
constructor( constructor(
private readonly buildWarnung: DrawWarnung,
private readonly buildBandOben: DrawBandOben, private readonly buildBandOben: DrawBandOben,
private readonly buildSieb: Sieb, private readonly buildSieb: Sieb,
private readonly buildGurtfoerderer: DrawGurtfoerderer, private readonly buildGurtfoerderer: DrawGurtfoerderer,
@@ -63,6 +66,21 @@ export class DrawService {
return this.buildBandOben.getObject(config, options); return this.buildBandOben.getObject(config, options);
} }
renderGraphic(type: string, input: unknown) {
switch (type) {
case 'warnung': {
const { config, options } = parseWarnungRequest(input);
return this.buildWarnung.getObject(config, options);
}
case 'bandOben': return this.renderBandOben(input);
case 'motor': {
const { config, options } = parseMotorRequest(input);
return this.buildMotor.getObject(config, options);
}
default: throw new NotFoundException('Unbekannter POST-Grafiktyp: ' + type);
}
}
sieb(options?: DrawShapeOptionenDto, rawSvg?: boolean) { sieb(options?: DrawShapeOptionenDto, rawSvg?: boolean) {
if (rawSvg) return this.buildSieb.getSvg(options); if (rawSvg) return this.buildSieb.getSvg(options);
return this.buildSieb.getDrawObject(options); return this.buildSieb.getDrawObject(options);
+36 -12
View File
@@ -341,21 +341,45 @@ export class DrawAnlageDurmin {
let ba3_pos_hf_x = 750 let ba3_pos_hf_x = 750
let ba3_pos_hf_y = 770 //anfanf(B1) 130 B2 310; B3 ende 520 let ba3_pos_hf_y = 770 //anfanf(B1) 130 B2 310; B3 ende 520
group1.add(this.createBand({ posX: 100, posY: 20, width: zufuefband_l, height: zufuefband_b, nordSued: true, boxEnde: true })) // BA1 Zufuehrband /* group1.add(new DrawLine({x1:0,y1:100,x2:1500,y2:100}));
group1.add(this.createBand({ posX: ba1_pos_hf_x, posY: ba1_pos_hf_y, width: verteilband_l, height: verteilband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA1 Verteilband group1.add(new DrawLine({x1:0,y1:110,x2:1500,y2:110}));
group1.add(this.createBand({ posX: ba1_pos_hf_x - (kopfband_l / 2 - verteilband_b / 2), posY: ba1_pos_hf_y - (kopfband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA2 Kopfband hinten group1.add(new DrawLine({x1:0,y1:120,x2:1500,y2:120}));
group1.add(this.createBand({ posX: ba1_pos_hf_x - (kopfband_l / 2 - verteilband_b / 2), posY: ba1_pos_hf_y + verteilband_l - (kopfband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA2 Kopfband vorne group1.add(new DrawLine({x1:0,y1:130,x2:1500,y2:130}));
group1.add(new DrawLine({x1:0,y1:140,x2:1500,y2:140}));
group1.add(new DrawLine({x1:0,y1:150,x2:1500,y2:150}));
group1.add(new DrawLine({x1:0,y1:160,x2:1500,y2:160}));
group1.add(new DrawLine({x1:0,y1:170,x2:1500,y2:170}));
group1.add(new DrawLine({x1:0,y1:180,x2:1500,y2:180}));
group1.add(new DrawLine({x1:0,y1:190,x2:1500,y2:190}));
group1.add(new DrawLine({x1:0,y1:200,x2:1500,y2:200}));
group1.add(new DrawLine({x1:10,y1:0,x2:10,y2:1100}));
group1.add(new DrawLine({x1:20,y1:0,x2:20,y2:1100}));
group1.add(new DrawLine({x1:30,y1:0,x2:30,y2:1100}));
group1.add(new DrawLine({x1:40,y1:0,x2:40,y2:1100}));
group1.add(new DrawLine({x1:50,y1:0,x2:50,y2:1100}));
group1.add(new DrawLine({x1:60,y1:0,x2:60,y2:1100}));
group1.add(new DrawLine({x1:70,y1:0,x2:70,y2:1100}));
group1.add(new DrawLine({x1:80,y1:0,x2:80,y2:1100}));
group1.add(new DrawLine({x1:90,y1:0,x2:90,y2:1100}));
group1.add(new DrawLine({x1:100,y1:0,x2:100,y2:1100}));
*/
//group1.add(this.createBand({ posX: 100, posY: 20, width: zufuefband_l, height: zufuefband_b, nordSued: true, boxEnde: true })) // BA1 Zufuehrband
//group1.add(this.createBand({ posX: ba1_pos_hf_x, posY: ba1_pos_hf_y, width: verteilband_l, height: verteilband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA1 Verteilband
//group1.add(this.createBand({ posX: ba1_pos_hf_x - (kopfband_l / 2 - verteilband_b / 2), posY: ba1_pos_hf_y - (kopfband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA2 Kopfband hinten
//group1.add(this.createBand({ posX: ba1_pos_hf_x - (kopfband_l / 2 - verteilband_b / 2), posY: ba1_pos_hf_y + verteilband_l - (kopfband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA2 Kopfband vorne
group1.add(this.createBand({ posX: 340, posY: 240, width: zufuefband_l + 400, height: zufuefband_b, nordSued: false, boxStart: true, boxEnde: true }))// BA2 Zufuehrband //group1.add(this.createBand({ posX: 340, posY: 240, width: zufuefband_l + 400, height: zufuefband_b, nordSued: false, boxStart: true, boxEnde: true }))// BA2 Zufuehrband
group1.add(this.createBand({ posX: ba2_pos_hf_x, posY: ba2_pos_hf_y, width: verteilband_l, height: verteilband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA1 Verteilband //group1.add(this.createBand({ posX: ba2_pos_hf_x, posY: ba2_pos_hf_y, width: verteilband_l, height: verteilband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA1 Verteilband
group1.add(this.createBand({ posX: ba2_pos_hf_x - (kopfband_b / 2), posY: ba2_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband hinten //group1.add(this.createBand({ posX: ba2_pos_hf_x - (kopfband_b / 2), posY: ba2_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband hinten
group1.add(this.createBand({ posX: ba2_pos_hf_x + verteilband_l - (kopfband_b / 2), posY: ba2_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband vorne //group1.add(this.createBand({ posX: ba2_pos_hf_x + verteilband_l - (kopfband_b / 2), posY: ba2_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband vorne
group1.add(this.createBand({ posX: 360, posY: 900, width: zufuefband_l + 400, height: zufuefband_b, nordSued: false, boxStart: true, boxEnde: true }))// BA2 Zufuehrband //group1.add(this.createBand({ posX: 360, posY: 900, width: zufuefband_l + 400, height: zufuefband_b, nordSued: false, boxStart: true, boxEnde: true }))// BA2 Zufuehrband
group1.add(this.createBand({ posX: ba3_pos_hf_x, posY: ba3_pos_hf_y, width: verteilband_l, height: verteilband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA1 Verteilband //group1.add(this.createBand({ posX: ba3_pos_hf_x, posY: ba3_pos_hf_y, width: verteilband_l, height: verteilband_b, nordSued: false, boxEnde: true, boxStart: true }))// BA1 Verteilband
group1.add(this.createBand({ posX: ba3_pos_hf_x - (kopfband_b / 2), posY: ba3_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband hinten //group1.add(this.createBand({ posX: ba3_pos_hf_x - (kopfband_b / 2), posY: ba3_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband hinten
group1.add(this.createBand({ posX: ba3_pos_hf_x + verteilband_l - (kopfband_b / 2), posY: ba3_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband vorne //group1.add(this.createBand({ posX: ba3_pos_hf_x + verteilband_l - (kopfband_b / 2), posY: ba3_pos_hf_y - (kopfband_l / 2) + (verteilband_b / 2), width: kopfband_l, height: kopfband_b, nordSued: true, boxEnde: true, boxStart: true }))// BA2 Kopfband vorne
group1.add(zBa1Schine1); group1.add(zBa1Schine1);
group1.add(zBa1Schine2); group1.add(zBa1Schine2);
+51 -4
View File
@@ -12,10 +12,57 @@ describe('BandOben render', () => {
const result = new DrawBandOben().getObject({ width: 40, length: 200 }, { fromNorthToSouth, trichterStart }); const result = new DrawBandOben().getObject({ width: 40, length: 200 }, { fromNorthToSouth, trichterStart });
expect(result.width).toBe(width); expect(result.width).toBe(width);
expect(result.height).toBe(height); expect(result.height).toBe(height);
expect(result.svg[0].data).toContain('<svg xmlns='); expect(result.varianten[0].svg).toContain('<svg xmlns=');
expect(result.svg[0].data).toContain('viewBox="0 0 ' + width + ' ' + height + '"'); expect(result.varianten[0].svg).toContain('viewBox="0 0 ' + width + ' ' + height + '"');
expect(result.xaml[0].data).toContain('<Viewbox xmlns='); expect(result.varianten[0].xaml).toContain('<Viewbox Stretch="None" StretchDirection="Both" Width="' + width + '" Height="' + height + '" xmlns=');
expect(result.xaml[0].data).toContain('Width="' + width + '" Height="' + height + '"'); expect(result.varianten[0].xaml).toContain('Width="' + width + '" Height="' + height + '"');
});
it.each([false, true])('liefert Statuspunkte mittig und über dem Band (Nord-Süd %s)', fromNorthToSouth => {
const result = new DrawBandOben().getObject({ width: 40, length: 200 }, { fromNorthToSouth, trichterStart: true });
expect(result.varianten.map(item => item.state)).toEqual(['inactive', 'active', 'error']);
result.varianten.forEach(item => expect(Buffer.from(item.xamlBase64, 'base64').toString('utf8')).toBe(item.xaml));
expect(result.varianten[0].svg).not.toContain('<ellipse');
for (const [index, color] of [[1, '#00f000'], [2, '#f00000']] as const) {
const svg = result.varianten[index].svg;
expect(svg).toContain('cx="' + result.width / 2 + '"');
expect(svg).toContain('cy="' + result.height / 2 + '"');
expect(svg).toContain('fill="' + color + '"');
expect(svg.lastIndexOf('<ellipse')).toBeGreaterThan(svg.lastIndexOf('<path'));
expect(result.varianten[index].xaml).toContain('Fill="' + color + '"');
expect(result.varianten[index].xaml).toContain('<Ellipse');
}
});
it.each([
[false, true, false], [true, true, false],
[false, false, true], [true, false, true],
[false, true, true], [true, true, true],
])('setzt die äußere Referenzbox lokal auf 0,0 (%s, %s, %s)', (nordSued, boxStart, boxEnde) => {
const result = new DrawBandOben().createBand({ width: 40, height: 200, posX: 0, posY: 0, nordSued, boxStart, boxEnde });
const svg = result.band.getChildString(false, 0);
const xaml = result.band.getChildString(true, 0);
expect(svg).toMatch(/d="M 0 0[^"]*"[^>]*fill="#e0e0e0"/);
expect(xaml).toMatch(/Data="M 0,0[^"]*"[^>]*Fill="#e0e0e0"/);
if (!boxStart) {
expect(svg).toContain(nordSued ? 'M 5 -180' : 'M -180 5');
}
});
it.each([
[false, false, false], [true, false, false],
[false, true, false], [true, true, false],
[false, false, true], [true, false, true],
[false, true, true], [true, true, true],
])('übernimmt die tatsächlichen Gesamtmaße auch bei kleinen Bändern (%s, %s, %s)', (fromNorthToSouth, trichterStart, trichterEnd) => {
const config = { width: 12, length: 30 };
const options = { fromNorthToSouth, trichterStart, trichterEnd };
const result = new DrawBandOben().getObject(config, options);
const crossSize = 12 + (trichterStart || trichterEnd ? 10 : 0) + 2;
expect(result.width).toBe(fromNorthToSouth ? crossSize : 32);
expect(result.height).toBe(fromNorthToSouth ? 32 : crossSize);
expect(result.varianten[1].svg).toContain('cx="' + result.width / 2 + '"');
expect(result.varianten[1].svg).toContain('cy="' + result.height / 2 + '"');
}); });
it('setzt fehlende Optionen auf false und erhält explizites false', () => { it('setzt fehlende Optionen auf false und erhält explizites false', () => {
+41 -13
View File
@@ -107,9 +107,23 @@ export class DrawBandOben implements GraphicGenerator<BandObenConfig, BandObenOp
]; ];
// Lokaler Ursprung: äußere Startbox, sonst äußere Endbox, sonst Bandanfang.
const anchor = data.boxStart ? pBandBoxStart[0] : data.boxEnde ? pBandBoxEnd[0] : pBand1[0];
const anchorX = anchor.type === 'M' ? anchor.x : 0;
const anchorY = anchor.type === 'M' ? anchor.y : 0;
for (const path of [pBand1, pBand2, pBandBoxStart, pBandBoxStartInnen, pBandBoxEnd, pBandBoxEndInnen]) {
const start = path[0];
if (start.type === 'M') {
path[0] = { ...start, x: start.x - anchorX, y: start.y - anchorY };
}
}
const group = new DrawGroup({}); const group = new DrawGroup({});
const ueberstand = data.boxStart || data.boxEnde ? boxUeberstand : 0; const ueberstand = data.boxStart || data.boxEnde ? boxUeberstand : 0;
group.setAtrr({ translate_y: posY + (nordSued ? 0 : ueberstand) + 1, translate_x: posX + (nordSued ? ueberstand : 0) + 1 }) // Dokumentrahmen berücksichtigt negative lokale Koordinaten sowie den Linienrand.
group.setAtrr({
translate_y: posY + anchorY + (nordSued ? 0 : ueberstand) + 1,
translate_x: posX + anchorX + (nordSued ? ueberstand : 0) + 1,
});
const belt1 = new DrawPath(pBand1); const belt1 = new DrawPath(pBand1);
belt1.setAtrr({ fill: "#404040", stroke: "#404040" }) belt1.setAtrr({ fill: "#404040", stroke: "#404040" })
@@ -143,6 +157,7 @@ export class DrawBandOben implements GraphicGenerator<BandObenConfig, BandObenOp
group.add(belt2) group.add(belt2)
group.add(belt1) group.add(belt1)
return { return {
band: group, band: group,
width: width + (nordSued ? 2 * ueberstand : 0) + 2, width: width + (nordSued ? 2 * ueberstand : 0) + 2,
@@ -172,19 +187,32 @@ export class DrawBandOben implements GraphicGenerator<BandObenConfig, BandObenOp
} }
getObject(config: BandObenConfig, options?: Partial<BandObenOptions>): DrawDataDto { getObject(config: BandObenConfig, options?: Partial<BandObenOptions>): DrawDataDto {
const beldData = this.create(config,options) const bandData = this.create(config, options);
const bedlWithHeader = this.createObjectWithHeader(beldData.group,beldData.width,beldData.height); const states = ['inactive', 'active', 'error'] as const;
const graphics = states.map(state => {
const xaml = bedlWithHeader.getChildString(true,0); const group = new DrawGroup({});
const svg = bedlWithHeader.getChildString(false, 0) if (state !== 'inactive') {
const radius = config.width * 0.15;
return { const color = state === 'active' ? this.green : this.red;
name: "bandOben", const point = new DrawEllipse({
height: beldData.height, cx: bandData.width / 2, cy: bandData.height / 2, rx: radius, ry: radius,
width: beldData.width, });
svg:[{state:'inactive',data:svg}], point.setAtrr({ fill: color, stroke: color });
xaml:[{state:'inactive',data:xaml}] // DrawGroup gibt die Elemente rückwärts aus: Punkt über dem Band.
group.add(point);
} }
group.add(bandData.group);
const header = this.createObjectWithHeader(group, bandData.width, bandData.height);
const xaml = header.getChildString(true, 0).replace(
'<Viewbox ',
`<Viewbox Stretch="None" StretchDirection="Both" Width="${bandData.width}" Height="${bandData.height}" `,
);
return { state, svg: header.getChildString(false, 0), xaml };
});
return {
name: 'bandOben', width: bandData.width, height: bandData.height,
varianten: graphics.map(item => ({ ...item, xamlBase64: Buffer.from(item.xaml, 'utf8').toString('base64') })),
};
} }
createObjectWithHeader(group:DrawGroup,width:number,height:number):DrawHeader{ createObjectWithHeader(group:DrawGroup,width:number,height:number):DrawHeader{
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from '@jest/globals';
import { DrawMotor } from './drawMotor';
import { parseMotorRequest } from '../../_dto/motor.dto';
describe('Motor getObject', () => {
it('liefert drei Zustände als vollständiges SVG und XAML', () => {
const result = new DrawMotor().getObject({ scale: 2, raster: 4 });
expect(result.width).toBe(24);
expect(result.height).toBe(24);
expect(result.varianten.map(item => item.state)).toEqual(['inactive', 'active', 'error']);
result.varianten.forEach(item => expect(item.svg).toContain('<svg xmlns='));
result.varianten.forEach(item => expect(item.xaml).toContain('<Viewbox xmlns='));
result.varianten.forEach(item => expect(Buffer.from(item.xamlBase64, 'base64').toString('utf8')).toBe(item.xaml));
expect(result.varianten[1].svg).toContain('#00f000');
expect(result.varianten[2].xaml).toContain('#f00000');
});
it('übernimmt Farben und behält bestehende GET-Ausgaben bei', () => {
const generator = new DrawMotor();
expect(generator.getObject({ scale: 1, raster: 10 }, { colorActive: '#123456' }).varianten[1].svg).toContain('#123456');
expect(generator.getDrawObject({}).px_width).toBe(24);
expect(generator.getSvg({})).toContain('<svg');
});
it('setzt Standardwerte bei leerer config', () => {
expect(parseMotorRequest({ config: {} })).toEqual({ config: { scale: 2, raster: 4 }, options: {} });
});
it.each([1, 2, 4])('zentriert das M in beiden Formaten bei Skalierung %s', scale => {
const size = 3 * 4 * scale;
const result = new DrawMotor().getObject({ scale, raster: 4 });
for (const { svg: data } of result.varianten) {
expect(data).toContain('x="' + size / 2 + '" y="' + size / 2 + '"');
expect(data).toContain('text-anchor="middle" dominant-baseline="central"');
expect(data).toContain('font-size="' + size * 0.6 + '"');
expect(data).toContain('>M</text>');
expect(data.indexOf('<ellipse')).toBeLessThan(data.indexOf('<text'));
}
for (const { xaml: data } of result.varianten) {
expect(data).toContain('<Grid Canvas.Left="0" Canvas.Top="0" Width="' + size + '" Height="' + size + '">');
expect(data).toContain('Text="M"');
expect(data).toContain('FontSize="' + size * 0.6 + '"');
expect(data).toContain('HorizontalAlignment="Center" VerticalAlignment="Center"');
}
});
it.each([null, {}, { config: { scale: 0 } }, { config: { raster: '4' } },
{ config: {}, options: { colorActive: 'red' } }, { config: { unbekannt: 1 } }])('verhindert ungültige Eingaben %j', value => {
expect(() => parseMotorRequest(value)).toThrow();
});
});
+28 -6
View File
@@ -5,7 +5,9 @@ import { DrawEllipse } from "../lib/drawEllipse";
import { cal_rotation_dim } from '../lib/drawFunktions' import { cal_rotation_dim } from '../lib/drawFunktions'
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import { DrawDto, DrawShapeOptionenDto } from "src/_dto/draw.dto"; import { DrawDataDto, DrawDto, DrawShapeOptionenDto } from "src/_dto/draw.dto";
import type { GraphicGenerator } from './graphic-generator';
import type { MotorConfig, MotorOptions } from './types';
import { DrawHeader } from "../lib/drawHeader"; import { DrawHeader } from "../lib/drawHeader";
interface Para { interface Para {
@@ -14,7 +16,7 @@ interface Para {
@Injectable() @Injectable()
export class DrawMotor { export class DrawMotor implements GraphicGenerator<MotorConfig, MotorOptions> {
scale = 0; scale = 0;
winkel = 0; winkel = 0;
raster = 4; raster = 4;
@@ -35,9 +37,9 @@ export class DrawMotor {
create(optionen?: DrawShapeOptionenDto): DrawGroup { create(optionen?: DrawShapeOptionenDto): DrawGroup {
let color = this.normal; let color = optionen?.colorInactive ?? this.normal;
if (optionen && optionen.state == 'active') color = this.green; if (optionen && optionen.state == 'active') color = optionen.colorActive ?? this.green;
if (optionen && optionen.state == 'error') color = this.red; if (optionen && optionen.state == 'error') color = optionen.colorError ?? this.red;
let raster = 4.0; let raster = 4.0;
@@ -65,7 +67,10 @@ export class DrawMotor {
const z_kreis = new DrawEllipse({ cx: x_m, cy: y_m, rx: radius, ry: radius }); const z_kreis = new DrawEllipse({ cx: x_m, cy: y_m, rx: radius, ry: radius });
const z_text = new DrawText({ x: 5, y: 0, text:"M" }); const z_text = new DrawText({
x: 0, y: 0, text: "M",
centeredBox: { width: obj_w, height: obj_h, fontSize: obj_h * 0.6 },
});
z_kreis.setAtrr({ fill: color }) z_kreis.setAtrr({ fill: color })
@@ -86,6 +91,23 @@ export class DrawMotor {
}
getObject(config: MotorConfig, options?: Partial<MotorOptions>): DrawDataDto {
const width = 3 * config.raster * config.scale;
const states = ['inactive', 'active', 'error'] as const;
const graphics = states.map(state => {
const group = this.create({ ...config, ...options, state });
const header = new DrawHeader({ lenght: width, height: width });
header.add(group);
return { state, svg: header.getChildString(false, 0), xaml: header.getChildString(true, 0) };
});
return {
name: 'motor',
width,
height: width,
varianten: graphics.map(item => ({ ...item, xamlBase64: Buffer.from(item.xaml, 'utf8').toString('base64') })),
};
} }
getDrawObject(optionen?: DrawShapeOptionenDto): DrawDto { getDrawObject(optionen?: DrawShapeOptionenDto): DrawDto {
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, it } from '@jest/globals';
import { DrawWarnung, parseWarnungRequest } from './drawWarnung';
describe('Warnung ohne MinMax', () => {
it('liefert die Originalgeometrie als SVG, XAML und UTF-8-Base64', () => {
const { config, options } = parseWarnungRequest({ config: {} });
const result = new DrawWarnung().getObject(config, options);
expect(result.width).toBe(20);
expect(result.height).toBe(20);
expect(result.varianten).toHaveLength(1);
const variant = result.varianten[0];
expect(variant.svg).toContain('fill="#FAC44F" fill-rule="evenodd"');
expect(variant.xaml).toContain('FillRule="EvenOdd"');
expect(variant.xaml).toContain('Width="20" Height="20"');
expect(Buffer.from(variant.xamlBase64, 'base64').toString('utf8')).toBe(variant.xaml);
});
it('übernimmt Größe und Farbe', () => {
const { config, options } = parseWarnungRequest({ config: { width: 40, height: 30 }, options: { color: '#FF0000' } });
expect(new DrawWarnung().getObject(config, options).varianten[0].svg).toContain('fill="#FF0000"');
});
it.each([null, {}, { config: { width: -1 } }, { config: {}, options: { color: '<script>' } }])('weist ungültige Parameter zurück', input => {
expect(() => parseWarnungRequest(input)).toThrow();
});
});
+40
View File
@@ -0,0 +1,40 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import type { DrawDataDto } from '../../_dto/draw.dto';
import type { GraphicGenerator } from './graphic-generator';
export interface WarnungConfig { width: number; height: number }
export interface WarnungOptions { color: string }
export function parseWarnungRequest(input: unknown): { config: WarnungConfig; options: WarnungOptions } {
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value);
if (!object(input) || !object(input.config) || Object.keys(input).some(key => !['config', 'options'].includes(key)))
throw new BadRequestException('Erwartet werden config und optional options');
const options = input.options ?? {};
const width = input.config.width ?? 20, height = input.config.height ?? 20;
if (Object.keys(input.config).some(key => !['width', 'height'].includes(key)) ||
typeof width !== 'number' || !Number.isFinite(width) || width <= 0 ||
typeof height !== 'number' || !Number.isFinite(height) || height <= 0)
throw new BadRequestException('width und height müssen positive endliche Zahlen sein');
if (!object(options) || Object.keys(options).some(key => key !== 'color') ||
(options.color !== undefined && (typeof options.color !== 'string' || !/^#[0-9a-fA-F]{6}$/.test(options.color))))
throw new BadRequestException('options erlaubt color als Hexfarbe #RRGGBB');
return { config: { width, height }, options: { color: options.color as string ?? '#FAC44F' } };
}
@Injectable()
export class DrawWarnung implements GraphicGenerator<WarnungConfig, WarnungOptions> {
getObject(config: WarnungConfig, options?: Partial<WarnungOptions>): DrawDataDto {
const color = options?.color ?? '#FAC44F';
// Originalgeometrie aus „Warnung ohne MinMax.xaml“, einschließlich EvenOdd-Aussparungen.
const path = 'm 424.39268 319.47728 h -8.05519 c -0.36301 -0.36301 -0.36301 -0.95151 -1.1e-4 -1.31452 l 3.47998 -6.42969 c 0.3629 -0.36291 0.95141 -0.36291 1.31442 0 l 3.2609 6.42979 c 0.3629 0.36291 0.3629 0.95141 0 1.31442 z m -4.80212 -5.80912 0.38721 3.17549 h 0.77442 l 0.38728 -3.17549 z m 0.77442 3.64031 c -0.34209 0 -0.61958 0.27739 -0.61958 0.61958 0 0.3422 0.27749 0.61962 0.61958 0.61962 0.34219 0 0.61958 -0.27742 0.61958 -0.61962 0 -0.34219 -0.27739 -0.61958 -0.61958 -0.61958';
const svg = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${config.width}" height="${config.height}" viewBox="0 0 8.5996358 8.0163929"><g transform="translate(-416.06522 -311.46089)"><path d="${path}" fill="${color}" fill-rule="evenodd"/></g></svg>`;
const xaml = `<?xml version="1.0" encoding="UTF-8"?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Stretch="Uniform" Width="${config.width}" Height="${config.height}"><Canvas Width="8.5996358" Height="8.0163929"><Canvas><Canvas.RenderTransform><TranslateTransform X="-416.06522" Y="-311.46089"/></Canvas.RenderTransform><Path Fill="${color}" StrokeThickness="0.352777"><Path.Data><PathGeometry Figures="${path}" FillRule="EvenOdd"/></Path.Data></Path></Canvas></Canvas></Viewbox>`;
return {
name: 'warnung', ...config, varianten: [{
state: 'inactive', svg, xaml, xamlBase64: Buffer.from(xaml, 'utf8').toString('base64'),
}]
};
}
}
+10
View File
@@ -11,3 +11,13 @@ export interface BandObenConfig{
length:number, length:number,
width:number, width:number,
} }
export interface MotorConfig {
scale: number;
raster: number;
}
export interface MotorOptions {
colorInactive: string;
colorActive: string;
colorError: string;
}
+9
View File
@@ -5,6 +5,7 @@ interface PropText {
x: number, x: number,
y: number, y: number,
text:string text:string
centeredBox?: { width: number; height: number; fontSize: number };
} }
interface SvgOptions { interface SvgOptions {
@@ -37,6 +38,10 @@ export class DrawText extends DrawElement {
drawSvg() { drawSvg() {
const box = this.posAndText.centeredBox;
if (box) {
return `<text x="${this.posAndText.x + box.width / 2}" y="${this.posAndText.y + box.height / 2}" text-anchor="middle" dominant-baseline="central" font-family="Arial" font-size="${box.fontSize}" font-weight="bold" fill="#000000">${this.posAndText.text}</text>`;
}
const paraStr = this.convertAttributesToString(this.attributes); const paraStr = this.convertAttributesToString(this.attributes);
const posSvg = this.getSvgPositions(this.posAndText) const posSvg = this.getSvgPositions(this.posAndText)
const posStr = this.convertAttributesToString(posSvg); const posStr = this.convertAttributesToString(posSvg);
@@ -47,6 +52,10 @@ export class DrawText extends DrawElement {
} }
drawXaml(): string { drawXaml(): string {
const box = this.posAndText.centeredBox;
if (box) {
return `<Grid Canvas.Left="${this.posAndText.x}" Canvas.Top="${this.posAndText.y}" Width="${box.width}" Height="${box.height}"><TextBlock Text="${this.posAndText.text}" FontFamily="Arial" FontSize="${box.fontSize}" FontWeight="Bold" Foreground="#000000" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>`;
}
const paraStr = this.convertAttributesToString(this.attributes, true); const paraStr = this.convertAttributesToString(this.attributes, true);
//const posXaml = this.getXamlPositions(this.posAndText) //const posXaml = this.getXamlPositions(this.posAndText)
//const posStr = this.convertAttributesToString(posXaml, true); //const posStr = this.convertAttributesToString(posXaml, true);
@@ -0,0 +1,16 @@
import { Body, Controller, Get, HttpCode, Param, Post, Put } from '@nestjs/common';
import { SqlService } from './sql.service';
import { ProConVerbindungenDto } from '../../_dto/procon-verbindungen.dto';
@Controller('anlage/:anlageId/procon-verbindungen')
export class ProConVerbindungenController {
constructor(private readonly service: SqlService) {}
@Get()
list(@Param('anlageId') id: string) { return this.service.listConnections(id); }
@Put()
save(@Param('anlageId') id: string, @Body() dto: ProConVerbindungenDto) { return this.service.saveConnections(id, dto); }
@Post(':verbindungId/test')
@HttpCode(200)
test(@Param('anlageId') id: string, @Param('verbindungId') connectionId: string) { return this.service.testConnection(id, connectionId); }
}
+5
View File
@@ -1,8 +1,13 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { SqlService } from './sql.service'; import { SqlService } from './sql.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Anlage, AnlageSchema } from '../../_schemas/anlage.schema';
import { ProConVerbindungenController } from './procon-verbindungen.controller';
@Module({ @Module({
imports: [MongooseModule.forFeature([{ name: Anlage.name, schema: AnlageSchema }])],
controllers: [ProConVerbindungenController],
providers: [SqlService], providers: [SqlService],
exports: [SqlService] exports: [SqlService]
}) })
@@ -0,0 +1,91 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
jest.mock('mssql', () => ({ ConnectionPool: jest.fn() }));
import * as sql from 'mssql';
import { Types } from 'mongoose';
import { SqlService } from './sql.service';
import { parseVerbindungen } from '../../_dto/procon-verbindungen.dto';
describe('SQL-Verbindungen aus MongoDB', () => {
let service: SqlService;
let anlage: any;
let model: any;
let pools: any[];
const connection = () => ({
_id: new Types.ObjectId(), name: 'TestRechner', umgebung: 'test' as const,
server: 'localhost', instanz: 'SQLEXPRESS', port: null,
datenbank: 'TestDB', benutzer: 'test', passwort: 'beispiel',
encrypt: true, trustServerCertificate: true, connectionTimeoutMs: 3000,
});
beforeEach(() => {
jest.clearAllMocks();
pools = [];
(sql.ConnectionPool as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => {
const pool: any = {
on: jest.fn(),
close: jest.fn<() => Promise<void>>().mockResolvedValue(undefined),
request: () => ({ query: jest.fn<() => Promise<unknown>>().mockResolvedValue({ recordset: [{ Verbindungstest: 1 }] }) }),
};
pool.connect = jest.fn(async () => pool);
pools.push(pool);
return pool;
});
const item = connection();
anlage = { _id: new Types.ObjectId(), name: 'Anlage', anlageNr: 1667,
proConVerbindungen: [item], aktiveProConVerbindungId: item._id.toString(),
save: jest.fn<() => Promise<void>>().mockResolvedValue(undefined) };
model = { findById: () => ({ exec: async () => anlage }), findOne: () => ({ exec: async () => anlage }) };
service = new SqlService(model);
});
it('öffnet beim Erzeugen des Service keine SQL-Verbindung', () => {
expect(sql.ConnectionPool).not.toHaveBeenCalled();
});
it('verwendet die aktive Verbindung und teilt gleichzeitige Verbindungsaufbauten', async () => {
const [first, second] = await Promise.all([service.getPool('testXXX'), service.getPool('testXXX')]);
expect(first).toBe(second);
expect(sql.ConnectionPool).toHaveBeenCalledTimes(1);
expect(sql.ConnectionPool).toHaveBeenCalledWith(expect.objectContaining({
server: 'localhost', database: 'TestDB', options: expect.objectContaining({ instanceName: 'SQLEXPRESS' }),
}));
await service.onModuleDestroy();
expect(pools[0].close).toHaveBeenCalled();
});
it('baut nach geänderten Einstellungen neu auf und schließt den alten Pool', async () => {
await service.getPool();
anlage.proConVerbindungen[0].datenbank = 'AndereDB';
await service.getPool();
expect(sql.ConnectionPool).toHaveBeenCalledTimes(2);
expect(pools[0].close).toHaveBeenCalledTimes(1);
});
it('verbindet sich ohne aktive Auswahl nicht automatisch mit einer Datenbank', async () => {
anlage.aktiveProConVerbindungId = null;
await expect(service.getPool()).rejects.toThrow('aktivieren');
expect(sql.ConnectionPool).not.toHaveBeenCalled();
});
it('testet auch eine inaktive Verbindung und schließt den Testpool', async () => {
anlage.aktiveProConVerbindungId = null;
await expect(service.testConnection(anlage._id.toString(), anlage.proConVerbindungen[0]._id.toString()))
.resolves.toEqual(expect.objectContaining({ success: true }));
expect(pools[0].close).toHaveBeenCalledTimes(1);
});
it('speichert Zugangsdaten und Auswahl und schließt bisherige Pools', async () => {
await service.getPool();
const item = anlage.proConVerbindungen[0];
const { _id, ...fields } = item;
await service.saveConnections(anlage._id.toString(), {
verbindungen: [{ ...fields, id: _id.toString() }], aktiveVerbindungId: _id.toString(),
});
expect(anlage.save).toHaveBeenCalled();
expect(anlage.proConVerbindungen[0].passwort).toBe('beispiel');
expect(pools[0].close).toHaveBeenCalled();
});
it('verhindert ungültige Ports, widersprüchliche Instanzen und fremde aktive IDs', () => {
const { _id, ...fields } = connection();
const parse = (changes: object, active: string | null = _id.toString()) => parseVerbindungen({
verbindungen: [{ ...fields, id: _id.toString(), ...changes }], aktiveVerbindungId: active,
});
expect(() => parse({ port: 1433 })).toThrow('entweder Instanz oder Port');
expect(() => parse({ instanz: '', port: 99999 })).toThrow('Port');
expect(() => parse({}, new Types.ObjectId().toString())).toThrow('Aktive Verbindung');
});
});
+104 -71
View File
@@ -1,84 +1,117 @@
import { Injectable, OnModuleInit, OnModuleDestroy, ServiceUnavailableException } from '@nestjs/common'; import { BadRequestException, Injectable, NotFoundException, OnModuleDestroy, ServiceUnavailableException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import * as sql from 'mssql'; import * as sql from 'mssql';
import { Anlage } from '../../_schemas/anlage.schema';
import type { ProConVerbindung } from '../../_schemas/procon-verbindung';
import { parseVerbindungen, ProConVerbindungenDto } from '../../_dto/procon-verbindungen.dto';
@Injectable() @Injectable()
export class SqlService implements OnModuleInit, OnModuleDestroy { export class SqlService implements OnModuleDestroy {
private pool: sql.ConnectionPool; private readonly pools = new Map<string, { signature: string; pool: Promise<sql.ConnectionPool> }>();
private pools = new Map<string, sql.ConnectionPool>(); constructor(@InjectModel(Anlage.name) private readonly anlagen: Model<Anlage>) {}
private configs = { private async getAnlage(id: string) {
testXXX: { if (!Types.ObjectId.isValid(id)) throw new BadRequestException('Ungültige Anlagen-ID');
user: 'sa', const anlage = await this.anlagen.findById(id).exec();
password: 'masterkey', if (!anlage) throw new NotFoundException('Anlage nicht gefunden');
server: 'WSRKSL01\\SQLEXPRESS', return anlage;
// server: '1659SERVER\\SQLEXPRESS', }
database: 'proConDaten',
}, private config(connection: ProConVerbindung): sql.config {
anlage2: { return {
user: 'sa', server: connection.server, database: connection.datenbank,
password: 'masterkey', user: connection.benutzer, password: connection.passwort,
server: 'WSRKSL01\\SQLEXPRESS', ...(connection.port !== null ? { port: connection.port } : {}),
database: 'proConDaten', connectionTimeout: connection.connectionTimeoutMs,
options: {
encrypt: connection.encrypt, trustServerCertificate: connection.trustServerCertificate,
...(connection.instanz ? { instanceName: connection.instanz } : {}),
}, },
}; };
}
async onModuleInit() { async listConnections(id: string) {
this.pool = await sql.connect({ const anlage = await this.getAnlage(id);
user: 'sa', return {
password: 'masterkey', anlageId: id, name: anlage.name, anlageNr: anlage.anlageNr,
server: 'WSRKSL01\\SQLEXPRESS', aktiveVerbindungId: anlage.aktiveProConVerbindungId ?? null,
database: 'proConDaten', verbindungen: (anlage.proConVerbindungen ?? []).map(connection => ({
options: { id: connection._id.toString(), name: connection.name, umgebung: connection.umgebung,
trustServerCertificate: true, server: connection.server, instanz: connection.instanz, port: connection.port,
}, datenbank: connection.datenbank, benutzer: connection.benutzer, passwort: connection.passwort,
encrypt: connection.encrypt, trustServerCertificate: connection.trustServerCertificate,
connectionTimeoutMs: connection.connectionTimeoutMs,
})),
};
}
async saveConnections(id: string, dto: ProConVerbindungenDto) {
const anlage = await this.getAnlage(id);
const parsed = parseVerbindungen(dto);
anlage.proConVerbindungen = parsed.verbindungen;
anlage.aktiveProConVerbindungId = parsed.aktiveVerbindungId;
await anlage.save();
await this.closeForAnlage(id);
return this.listConnections(id);
}
private async closeForAnlage(id: string) {
for (const [key, entry] of this.pools) {
if (!key.startsWith(id + ':')) continue;
this.pools.delete(key);
await entry.pool.then(pool => pool.close()).catch(() => undefined);
}
}
async getPool(anlage?: string): Promise<sql.ConnectionPool> {
// Alte Test-Aliase verwenden nun bewusst die ausgewählte Anlage und deren aktive Verbindung.
const item = anlage && Types.ObjectId.isValid(anlage)
? await this.getAnlage(anlage)
: !anlage || ['testXXX', 'anlage2'].includes(anlage)
? await this.anlagen.findOne({ selected: true }).exec()
: null;
if (!item) throw new NotFoundException('Keine passende Anlage ausgewählt');
const connection = item.proConVerbindungen?.find(value => value._id.toString() === item.aktiveProConVerbindungId);
if (!connection) throw new BadRequestException('Für diese Anlage zuerst eine ProCon-Verbindung speichern und aktivieren');
const key = item._id.toString() + ':' + connection._id.toString();
const config = this.config(connection);
const signature = JSON.stringify(config);
const cached = this.pools.get(key);
if (cached?.signature === signature) return cached.pool;
if (cached) {
this.pools.delete(key);
await cached.pool.then(pool => pool.close()).catch(() => undefined);
}
const pool = new sql.ConnectionPool(config);
pool.on('error', () => { if (this.pools.get(key)?.pool === pending) this.pools.delete(key); });
const pending = pool.connect().catch(async () => {
if (this.pools.get(key)?.pool === pending) this.pools.delete(key);
await pool.close().catch(() => undefined);
throw new ServiceUnavailableException('ProCon-Verbindung „' + connection.name + '“ ist nicht erreichbar');
}); });
this.pools.set(key, { signature, pool: pending });
return pending;
}
async testConnection(id: string, connectionId: string) {
const anlage = await this.getAnlage(id);
const connection = anlage.proConVerbindungen?.find(value => value._id.toString() === connectionId);
if (!connection) throw new NotFoundException('Gespeicherte Verbindung nicht gefunden');
const pool = new sql.ConnectionPool(this.config(connection));
try {
await pool.connect();
await pool.request().query('SELECT 1 AS Verbindungstest');
return { success: true, message: 'Verbindung erfolgreich: ' + connection.name };
} catch {
throw new ServiceUnavailableException('Verbindung fehlgeschlagen. Server, Zugangsdaten und Erreichbarkeit prüfen.');
} finally { await pool.close().catch(() => undefined); }
} }
async onModuleDestroy() { async onModuleDestroy() {
await this.pool?.close(); const entries = [...this.pools.values()];
} this.pools.clear();
await Promise.allSettled(entries.map(entry => entry.pool.then(pool => pool.close())));
getPool2(): sql.ConnectionPool {
return this.pool;
}
async getPool(anlage: string): Promise<sql.ConnectionPool> {
const existingPool = this.pools.get(anlage);
if (existingPool?.connected) {
return existingPool;
}
const config = this.configs[anlage];
if (!config) {
throw new Error(`Unbekannte Anlage: ${anlage}`);
}
try {
const pool = await new sql.ConnectionPool({
user: config.user,
password: config.password,
server: config.server,
database: config.database,
options: {
trustServerCertificate: true,
},
connectionTimeout: 3000,
}).connect();
this.pools.set(anlage, pool);
return pool;
} catch (error:any) {
console.error(
`Datenbank für ${anlage} nicht erreichbar:`,
error.message,
);
throw new ServiceUnavailableException(
`Die Datenbank der ${anlage} ist momentan nicht erreichbar.`,
);
}
} }
} }
@@ -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;
}
+34 -2
View File
@@ -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 { 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') @Controller('procon/aggregate')
export class AggregateController { 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() @Get()
getAll() { getAll() {
return this.service.getAllAggregate(); return this.service.getAllAggregate();
} }
@Get(':id/visualisierungen')
getVisualisierungen(@Param('id', ParseIntPipe) id: number) {
return this.service.getVisualisierungen(id);
}
@Get('/byId/:id') @Get('/byId/:id')
getAggregateById(@Param('id') id: number) { getAggregateById(@Param('id') id: number) {
return this.service.getById(id); return this.service.getById(id);
+16 -1
View File
@@ -5,13 +5,28 @@ import { SqlModule } from 'src/infrastructure/sql/sql.module';
import { AggregateRepository } from './aggregate.repository'; import { AggregateRepository } from './aggregate.repository';
import { VisualisierungenService } from '../visualisierungen/visualisierungen.service'; import { VisualisierungenService } from '../visualisierungen/visualisierungen.service';
import { VisualisierungenModule } from '../visualisierungen/visualisierungen.module'; 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({ @Module({
imports: [ 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, SqlModule,
VisualisierungenModule VisualisierungenModule
], ],
providers: [AggregateService,AggregateRepository], providers: [AggregateService,AggregateRepository, AggregateMappingService, ProConSyncService],
controllers: [AggregateController] controllers: [AggregateController]
}) })
export class AggregateModule { } export class AggregateModule { }
+5 -3
View File
@@ -1,6 +1,7 @@
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import { ProConAggregateEntity } from "src/_sql/procon.Aggregat.entity"; import { ProConAggregateEntity } from "src/_sql/procon.Aggregat.entity";
import { SqlService } from "src/infrastructure/sql/sql.service"; import { SqlService } from "src/infrastructure/sql/sql.service";
import * as sql from 'mssql';
@Injectable() @Injectable()
export class AggregateRepository { export class AggregateRepository {
@@ -27,13 +28,14 @@ export class AggregateRepository {
const pool = await this.db.getPool(anlageId); const pool = await this.db.getPool(anlageId);
let where = ""; let where = "";
if (options.id) where += `id=${options.id}`; if (options.id !== undefined) where = 'Id=@id';
if (options.SPSAntriebId) where += `SPSAntriebId=${options.SPSAntriebId}`; 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 const result = await pool
.request() .request()
.input('id', sql.Int, options.id ?? options.SPSAntriebId)
.query(` .query(`
SELECT * SELECT *
FROM Aggregate FROM Aggregate
+7 -1
View File
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'; import { Injectable, NotFoundException } from '@nestjs/common';
import { AggregateRepository } from './aggregate.repository'; import { AggregateRepository } from './aggregate.repository';
import { VisualisierungenService } from '../visualisierungen/visualisierungen.service'; import { VisualisierungenService } from '../visualisierungen/visualisierungen.service';
@@ -14,6 +14,12 @@ export class AggregateService {
return this.repo.findAll(this.anlage) 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){ async getById(id:number){
const agg = await this.repo.findBy(this.anlage,{id:id}); const agg = await this.repo.findBy(this.anlage,{id:id});
if(!agg) return {success:false,error:"Aggregat nicht gefunden"} 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();
});
});
+296
View File
@@ -0,0 +1,296 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import * as sql from 'mssql';
import { createHash } from 'node:crypto';
import { Anlage } from '../../_schemas/anlage.schema';
import { ProConViewAggregate } from '../../_schemas/anlagen/procon-view-aggregate';
import type { ProConZuordnung } from '../../_schemas/anlagen/procon-zuordnung';
import { SqlService } from '../../infrastructure/sql/sql.service';
import { validateSyncXml } from './sync-xml';
import { DrawService } from '../../draw/draw.service';
import type { GrafikGeneratorDaten } from '../../_schemas/anlagen/procon-view-aggregate';
export interface SyncValues { x: number; y: number; width: number; height: number; show: boolean }
export interface SyncRequest {
version: string;
direction: 'toLocal' | 'toProcon' | 'saveLocal';
values: SyncValues;
viewId?: string;
state?: string;
xaml?: string;
xamlOnly?: boolean;
}
export interface GroupSyncValues extends SyncValues { z: number }
function validateGroupValues(values: GroupSyncValues) {
validateSyncValues(values);
if (!Number.isInteger(values.z)) throw new BadRequestException('Z-Index muss eine ganze Zahl sein');
}
export interface GroupSyncRequest {
version: string;
direction: 'toLocal' | 'toProcon' | 'saveLocal';
masterId: string;
elementIds?: string[];
elements?: { id: string; values: GroupSyncValues; generator?: GrafikGeneratorDaten }[];
}
export function validateSyncValues(values: SyncValues) {
if (!values || ['x', 'y', 'width', 'height'].some(key => typeof values[key] !== 'number' || !Number.isFinite(values[key])) ||
values.width < 0 || values.height < 0 || typeof values.show !== 'boolean')
throw new BadRequestException('Position und Maße müssen gültige Zahlen sein; Sichtbarkeit muss Boolean sein');
}
export function decodeXaml(value: string | null | undefined) {
if (!value) return '';
if (value.trimStart().startsWith('<')) return value;
return Buffer.from(value, 'base64').toString('utf8');
}
@Injectable()
export class ProConSyncService {
constructor(
@InjectModel(Anlage.name) private readonly anlagen: Model<Anlage>,
@InjectModel(ProConViewAggregate.name, 'anlagen') private readonly graphics: Model<ProConViewAggregate>,
@InjectModel('ProConZuordnung', 'anlagen') private readonly mappings: Model<ProConZuordnung>,
private readonly db: SqlService,
private readonly draw: DrawService,
) {}
private async verifyAggregate(pool: sql.ConnectionPool, aggregateId: number, mapping: ProConZuordnung) {
const result = await pool.request().input('agg', sql.Int, aggregateId).query(`
SELECT a.SPSAntriebId, (SELECT COUNT(*) FROM Aggregate b WHERE b.SPSAntriebId=a.SPSAntriebId) AS Anzahl
FROM Aggregate a WHERE a.Id=@agg`);
const row = result.recordset[0];
if (!row || row.SPSAntriebId !== mapping.spsAntriebId || row.Anzahl !== 1)
throw new BadRequestException('ProCon-IDs haben sich geaendert oder sind mehrdeutig. Unter Zuordnung Vorschlaege neu laden und aktualisieren.');
}
private async loadGroup(aggregateId: number) {
const anlage = await this.anlagen.findOne({ selected: true }).exec();
if (!anlage?.aktiveProConVerbindungId) throw new BadRequestException('Aktive Verbindung fehlt');
const context = { anlageId: anlage._id.toString(), verbindungId: anlage.aktiveProConVerbindungId };
const mapping = await this.mappings.findOne({ ...context, proConAggregateId: aggregateId }).lean().exec();
if (!mapping) throw new BadRequestException('Aggregat zuerst unter ProCon → Zuordnung zuordnen');
const document = await this.graphics.findOne({ visuAggregateId: mapping.visuAggregateId }).exec();
if (!document) throw new BadRequestException('Eigene Grafikelemente fehlen');
const pool = await this.db.getPool(context.anlageId);
await this.verifyAggregate(pool, aggregateId, mapping);
const rows = (await pool.request().input('agg', sql.Int, aggregateId)
.query('SELECT Id, PositionX, PositionY, PositionZ, Width, Height, Show FROM Visualisierungen WHERE AggregateId=@agg ORDER BY Id')).recordset;
const ids = mapping.elemente.map(item => item.elementId);
const remoteIds = mapping.elemente.map(item => item.visualizationId);
if (new Set(ids).size !== ids.length || new Set(remoteIds).size !== remoteIds.length)
throw new BadRequestException('Mehrdeutige Elementzuordnung. Zuordnung prüfen.');
const elements = document.elemente.map(element => {
const id = element._id!.toString();
const link = mapping.elemente.find(item => item.elementId === id);
const row = rows.find(item => item.Id === link?.visualizationId);
return {
id, key: element.key, typ: element.typ,
visualizationId: row ? row.Id as number : null,
local: { z: element.zIndex, x: element.posX, y: element.posY, width: element.width, height: element.height, show: element.show },
procon: row ? { z: row.PositionZ as number, x: row.PositionX as number, y: row.PositionY as number, width: row.Width as number, height: row.Height as number, show: !!row.Show } : null,
svg: element.darstellung === 'xaml' ? element.varianten.find(item => item.svg)?.svg ?? '' : '',
hasXaml: element.darstellung === 'xaml',
generator: element.darstellung === 'xaml' ? element.generator : undefined,
};
});
const main = elements.find(item => item.key === 'main');
const masterId = main?.id ?? document.positionsMasterId ?? '';
const version = createHash('sha256').update(JSON.stringify({
context, mapping, elements: elements.map(({ svg, ...item }) => item), masterId, revision: document.get('__v'),
})).digest('hex');
const current = await this.anlagen.findOne({ selected: true }).exec();
if (current?._id.toString() !== context.anlageId || current.aktiveProConVerbindungId !== context.verbindungId)
throw new BadRequestException('Anlage oder Verbindung geändert. Neu laden.');
return { context, document, pool, elements, masterId, mainId: main?.id ?? null, version };
}
async compareGroup(aggregateId: number) {
const data = await this.loadGroup(aggregateId);
return { ...data.context, elements: data.elements, masterId: data.masterId, mainId: data.mainId, version: data.version };
}
async applyGroup(aggregateId: number, dto: GroupSyncRequest) {
if (!dto || !['saveLocal', 'toLocal', 'toProcon'].includes(dto.direction)) throw new BadRequestException('Ungültige Richtung');
const data = await this.loadGroup(aggregateId);
if (dto.version !== data.version) throw new BadRequestException('Daten geändert. Arbeitsfläche neu laden.');
const masterId = data.mainId ?? dto.masterId;
if (!data.elements.some(item => item.id === masterId)) throw new BadRequestException('Positions-Master auswählen');
if (dto.direction === 'saveLocal') {
if (!Array.isArray(dto.elements) || dto.elements.length !== data.elements.length ||
new Set(dto.elements.map(item => item.id)).size !== data.elements.length ||
dto.elements.some(item => !data.elements.some(element => element.id === item.id)))
throw new BadRequestException('Elementliste unvollständig oder ungültig');
dto.elements.forEach(item => validateGroupValues(item.values));
}
if (dto.direction === 'toProcon') {
if (dto.elementIds !== undefined && (!Array.isArray(dto.elementIds) || !dto.elementIds.length ||
new Set(dto.elementIds).size !== dto.elementIds.length || dto.elementIds.some(id => !data.elements.some(item => item.id === id && item.procon))))
throw new BadRequestException('Ungueltige Elementauswahl fuer ProCon');
const mapped = data.elements.filter(item => item.procon && (!dto.elementIds || dto.elementIds.includes(item.id)));
if (!mapped.length) throw new BadRequestException('Keine zugeordneten ProCon-Visualisierungen');
const transaction = new sql.Transaction(data.pool);
await transaction.begin();
try {
for (const element of mapped) {
const previous = element.procon!;
const values = element.local;
validateGroupValues(values);
const result = await new sql.Request(transaction)
.input('id', sql.Int, element.visualizationId).input('agg', sql.Int, aggregateId)
.input('z', sql.Int, values.z).input('oldZ', sql.Int, previous.z)
.input('x', sql.Float, values.x).input('y', sql.Float, values.y)
.input('w', sql.Float, values.width).input('h', sql.Float, values.height).input('show', sql.Bit, values.show)
.input('oldX', sql.Float, previous.x).input('oldY', sql.Float, previous.y)
.input('oldW', sql.Float, previous.width).input('oldH', sql.Float, previous.height).input('oldShow', sql.Bit, previous.show)
.query(`UPDATE Visualisierungen SET PositionZ=@z,PositionX=@x,PositionY=@y,Width=@w,Height=@h,Show=@show
WHERE Id=@id AND AggregateId=@agg AND PositionZ=@oldZ AND PositionX=@oldX AND PositionY=@oldY AND Width=@oldW AND Height=@oldH AND Show=@oldShow`);
if (result.rowsAffected[0] !== 1) throw new BadRequestException('ProCon inzwischen geändert. Alle Änderungen werden zurückgerollt.');
}
await transaction.commit();
} catch (error) { await transaction.rollback().catch(() => undefined); throw error; }
} else {
for (const element of data.document.elemente) {
const entry = data.elements.find(item => item.id === element._id!.toString())!;
// Importwerte kommen ausschließlich aus der Fremd-DB, niemals aus Eingabefeldern.
const values = dto.direction === 'toLocal' ? entry.procon : dto.elements!.find(item => item.id === entry.id)!.values;
if (!values) continue;
validateGroupValues(values);
const resized = element.width !== values.width || element.height !== values.height;
element.zIndex = values.z; element.posX = values.x; element.posY = values.y; element.width = values.width; element.height = values.height; element.show = values.show;
if (resized) {
element.manuell = true;
if (element.darstellung === 'xaml' && element.generator) element.generator.ergebnis = undefined;
}
const generator = dto.direction === 'saveLocal' ? dto.elements!.find(item => item.id === entry.id)!.generator : undefined;
if (generator !== undefined) {
if (element.darstellung !== 'xaml' || !generator || typeof generator !== 'object')
throw new BadRequestException('Nur XAML-Elemente verwenden einen Grafikgenerator');
const { grafikTyp, config, options } = generator;
const ergebnis = this.draw.renderGraphic(grafikTyp, { config, options });
element.generator = { grafikTyp, config, options: options ?? {}, ergebnis };
element.manuell = false;
element.width = ergebnis.width; element.height = ergebnis.height;
element.varianten = ergebnis.varianten.map(variant => ({
zustand: variant.state, svg: variant.svg, xaml: variant.xaml, xamlBase64: variant.xamlBase64,
}));
}
}
data.document.positionsMasterId = masterId;
data.document.markModified('elemente');
await data.document.validate();
const result = await this.graphics.updateOne({ _id: data.document._id, __v: data.document.get('__v') }, {
$set: { elemente: data.document.toObject().elemente, positionsMasterId: masterId }, $inc: { __v: 1 },
});
if (result.matchedCount !== 1) throw new BadRequestException('Eigene Daten inzwischen geändert. Neu laden.');
}
return this.compareGroup(aggregateId);
}
private async load(aggregateId: number, visualizationId: number) {
const anlage = await this.anlagen.findOne({ selected: true }).exec();
if (!anlage?.aktiveProConVerbindungId) throw new BadRequestException('Aktive Verbindung fehlt');
const context = { anlageId: anlage._id.toString(), verbindungId: anlage.aktiveProConVerbindungId };
const mapping = await this.mappings.findOne({ ...context, proConAggregateId: aggregateId }).lean().exec();
const link = mapping?.elemente.find(item => item.visualizationId === visualizationId);
if (!mapping || !link) throw new BadRequestException('Diese Visualisierung zuerst unter ProCon → Zuordnung zuordnen');
const document = await this.graphics.findOne({ visuAggregateId: mapping.visuAggregateId }).exec();
const element = document?.elemente.find(item => item._id?.toString() === link.elementId);
if (!document || !element) throw new BadRequestException('Zugeordnetes eigenes Element fehlt. Zuordnung prüfen.');
const pool = await this.db.getPool(context.anlageId);
await this.verifyAggregate(pool, aggregateId, mapping);
const remote = await pool.request().input('id', sql.Int, visualizationId).input('agg', sql.Int, aggregateId)
.query('SELECT Id, PositionX, PositionY, Width, Height, Show FROM Visualisierungen WHERE Id=@id AND AggregateId=@agg');
const row = remote.recordset[0];
if (!row) throw new BadRequestException('ProCon-Visualisierung nicht mehr vorhanden');
const views = element.darstellung === 'xaml'
? (await pool.request().input('id', sql.Int, visualizationId).query(`
SELECT DISTINCT v.Id, v.Data,
(SELECT COUNT(*) FROM Komponenten k2 WHERE k2.ViewId=v.Id) AS Verwendungen
FROM Komponenten k JOIN Views v ON v.Id=k.ViewId WHERE k.XamlVisualisierungId=@id ORDER BY v.Id
`)).recordset : [];
const local = { x: element.posX, y: element.posY, width: element.width, height: element.height, show: element.show };
const procon = { x: row.PositionX, y: row.PositionY, width: row.Width, height: row.Height, show: !!row.Show };
const variants = element.darstellung === 'xaml' ? element.varianten.map(item => ({
state: item.zustand, xaml: item.xaml || decodeXaml(item.xamlBase64),
})) : [];
const version = createHash('sha256').update(JSON.stringify({ context, link, local, procon, variants, views })).digest('hex');
const current = await this.anlagen.findOne({ selected: true }).exec();
if (current?._id.toString() !== context.anlageId || current.aktiveProConVerbindungId !== context.verbindungId)
throw new BadRequestException('Anlage oder Verbindung geändert. Neu laden.');
return { pool, document, element, context, local, procon, variants, views, version };
}
async compare(aggregateId: number, visualizationId: number) {
const data = await this.load(aggregateId, visualizationId);
return {
...data.context, version: data.version, key: data.element.key,
local: data.local, procon: data.procon, variants: data.variants,
views: data.views.map(view => ({ id: view.Id as string, xaml: decodeXaml(view.Data), usages: Number(view.Verwendungen) })),
};
}
async apply(aggregateId: number, visualizationId: number, dto: SyncRequest) {
if (!dto || !['toLocal', 'toProcon', 'saveLocal'].includes(dto.direction)) throw new BadRequestException('Ungültige Richtung');
const data = await this.load(aggregateId, visualizationId);
if (dto.version !== data.version) throw new BadRequestException('Daten haben sich geändert. Vergleich neu laden.');
if (dto.xamlOnly && dto.xaml === undefined) throw new BadRequestException('XAML fehlt');
const values = dto.xamlOnly ? (dto.direction === 'toProcon' ? data.procon : data.local)
: dto.direction === 'toLocal' ? data.procon : dto.values;
validateSyncValues(values);
const withXaml = dto.xaml !== undefined;
const xaml = dto.direction === 'toLocal' ? decodeXaml(data.views.find(view => view.Id === dto.viewId)?.Data) : dto.xaml;
if (withXaml && (data.element.darstellung !== 'xaml' || !dto.state || !/^[a-zA-Z0-9_-]+$/.test(dto.state)))
throw new BadRequestException('Eigenen XAML-Zustand auswählen');
if (withXaml && dto.direction !== 'saveLocal' && !data.views.some(view => view.Id === dto.viewId))
throw new BadRequestException('Zugeordnete ProCon-XAML-Datei auswählen');
if (withXaml && (typeof xaml !== 'string' || /<!DOCTYPE|<!ENTITY/i.test(xaml!) || (xaml!.trim() && !xaml!.trimStart().startsWith('<'))))
throw new BadRequestException('XAML muss XML-Text ohne DTD sein');
if (withXaml) validateSyncXml(xaml!);
if (dto.direction === 'toProcon') {
const transaction = new sql.Transaction(data.pool);
await transaction.begin();
try {
const result = await new sql.Request(transaction)
.input('id', sql.Int, visualizationId).input('agg', sql.Int, aggregateId)
.input('x', sql.Float, values.x).input('y', sql.Float, values.y)
.input('w', sql.Float, values.width).input('h', sql.Float, values.height).input('show', sql.Bit, values.show)
.input('oldX', sql.Float, data.procon.x).input('oldY', sql.Float, data.procon.y)
.input('oldW', sql.Float, data.procon.width).input('oldH', sql.Float, data.procon.height).input('oldShow', sql.Bit, data.procon.show)
.query(`UPDATE Visualisierungen SET PositionX=@x,PositionY=@y,Width=@w,Height=@h,Show=@show
WHERE Id=@id AND AggregateId=@agg AND PositionX=@oldX AND PositionY=@oldY AND Width=@oldW AND Height=@oldH AND Show=@oldShow`);
if (result.rowsAffected[0] !== 1) throw new BadRequestException('ProCon-Werte wurden inzwischen geändert. Neu laden.');
if (withXaml) {
const view = data.views.find(view => view.Id === dto.viewId)!;
const update = await new sql.Request(transaction).input('id', sql.NVarChar, dto.viewId)
.input('oldData', sql.NVarChar(sql.MAX), view.Data)
.input('data', sql.NVarChar(sql.MAX), Buffer.from(xaml!, 'utf8').toString('base64'))
.query('UPDATE Views SET Data=@data WHERE Id=@id AND (CONVERT(nvarchar(max),Data)=@oldData OR (Data IS NULL AND @oldData IS NULL))');
if (update.rowsAffected[0] !== 1) throw new BadRequestException('XAML wurde inzwischen geändert. Neu laden.');
}
await transaction.commit();
} catch (error) { await transaction.rollback().catch(() => undefined); throw error; }
} else {
data.element.posX = values.x; data.element.posY = values.y;
data.element.width = values.width; data.element.height = values.height; data.element.show = values.show;
data.element.manuell = true;
if (data.element.darstellung === 'xaml' && data.element.generator) data.element.generator.ergebnis = undefined;
if (withXaml && data.element.darstellung === 'xaml') {
const variant = { zustand: dto.state!, svg: '', xaml: xaml!, xamlBase64: Buffer.from(xaml!, 'utf8').toString('base64') };
const index = data.element.varianten.findIndex(item => item.zustand === dto.state);
if (index < 0) data.element.varianten.push(variant); else data.element.varianten[index] = variant;
// Vorhandenes SVG ist nach manueller XAML-Änderung keine verlässliche Vorschau.
}
data.document.markModified('elemente');
await data.document.validate();
const element = data.document.toObject().elemente.find(item => item._id?.toString() === data.element._id?.toString());
const result = await this.graphics.updateOne({
_id: data.document._id, __v: data.document.get('__v'),
'elemente._id': data.element._id,
}, { $set: { 'elemente.$': element }, $inc: { __v: 1 } });
if (result.matchedCount !== 1) throw new BadRequestException('Eigene Daten wurden inzwischen geändert. Neu laden.');
}
return this.compare(aggregateId, visualizationId);
}
}
+36
View File
@@ -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, private readonly repo: KomponentenRepository,
) { } ) { }
async getKomponenten(xamlVisuId: number) { async getKomponenten(xamlVisuId: number, anlage: string = this.anlage) {
const komponenten = await this.repo.findBy(this.anlage, xamlVisuId); const komponenten = await this.repo.findBy(anlage, xamlVisuId);
return komponenten; return komponenten;
} }
@@ -2,6 +2,7 @@ import { Injectable } from "@nestjs/common";
import { ProConAggregateEntity } from "src/_sql/procon.Aggregat.entity"; import { ProConAggregateEntity } from "src/_sql/procon.Aggregat.entity";
import { ProConVisualisierungenAggEntity, ProConVisualisierungenEntity } from "src/_sql/procon.Visualisierung.entity"; import { ProConVisualisierungenAggEntity, ProConVisualisierungenEntity } from "src/_sql/procon.Visualisierung.entity";
import { SqlService } from "src/infrastructure/sql/sql.service"; import { SqlService } from "src/infrastructure/sql/sql.service";
import * as sql from 'mssql';
@Injectable() @Injectable()
export class VisualisierungenRepository { export class VisualisierungenRepository {
@@ -27,7 +28,8 @@ export class VisualisierungenRepository {
AggregateId, AggregateId,
Number, Number,
PositionZ` 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; return result.recordset;
} }
@@ -45,6 +45,16 @@ export class VisualisierungenService {
return this.repo.getVisuaOfAgg(this.anlage, aggId) 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) { async updateMongoDB(aggId: number) {
/* const sqlAggData = await this.getVisuaAggData(aggId); /* const sqlAggData = await this.getVisuaAggData(aggId);
if (!sqlAggData) return; if (!sqlAggData) return;
@@ -0,0 +1,12 @@
import { Body, Controller, Get, Param, Put } from '@nestjs/common';
import { VisualisierungService } from './visualisierung.service';
import type { VisualisierungSettingsDto } from './visualisierung.dto';
@Controller('visualisierung')
export class VisualisierungController {
constructor(private readonly service: VisualisierungService) {}
@Get(':anlageId/settings')
get(@Param('anlageId') anlageId: string) { return this.service.get(anlageId); }
@Put(':anlageId/settings')
save(@Param('anlageId') anlageId: string, @Body() dto: VisualisierungSettingsDto) { return this.service.save(anlageId, dto); }
}
+27
View File
@@ -0,0 +1,27 @@
import { BadRequestException } from '@nestjs/common';
export interface VisualisierungSettingsDto {
workspaceWidth: number;
workspaceHeight: number;
grid: boolean;
gridStep: number;
snapToGrid: boolean;
showHidden: boolean;
selectedSpsAntriebId: number | null;
viewport: { x: number; y: number; width: number; height: number };
}
export const defaultSettings: VisualisierungSettingsDto = {
workspaceWidth: 2400, workspaceHeight: 1600, grid: true, gridStep: 10,
snapToGrid: false, showHidden: true, selectedSpsAntriebId: null,
viewport: { x: 0, y: 0, width: 2400, height: 1600 },
};
export function validateSettings(input: VisualisierungSettingsDto) {
const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
const size = (value: unknown) => finite(value) && value >= 1 && value <= 1000000;
if (!input || !size(input.workspaceWidth) || !size(input.workspaceHeight) || !size(input.gridStep) ||
!['grid', 'snapToGrid', 'showHidden'].every(key => typeof input[key] === 'boolean') ||
!(input.selectedSpsAntriebId === null || Number.isSafeInteger(input.selectedSpsAntriebId)) ||
!input.viewport || !finite(input.viewport.x) || !finite(input.viewport.y) ||
!size(input.viewport.width) || !size(input.viewport.height))
throw new BadRequestException('Ungueltige Visualisierungseinstellungen: Masse und Rasterweite muessen zwischen 1 und 1000000 liegen.');
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { Anlage, AnlageSchema } from '../_schemas/anlage.schema';
import { VisualisierungSettingsSchema } from '../_schemas/anlagen/visualisierung-settings';
import { VisualisierungController } from './visualisierung.controller';
import { VisualisierungService } from './visualisierung.service';
@Module({
imports: [MongooseModule.forFeature([{ name: Anlage.name, schema: AnlageSchema }]),
MongooseModule.forFeature([{ name: 'VisualisierungSettings', schema: VisualisierungSettingsSchema }], 'anlagen')],
controllers: [VisualisierungController], providers: [VisualisierungService],
})
export class VisualisierungModule {}
@@ -0,0 +1,34 @@
import { describe, expect, it, jest } from '@jest/globals';
import { VisualisierungService } from './visualisierung.service';
import { defaultSettings, validateSettings } from './visualisierung.dto';
describe('Visualisierungseinstellungen', () => {
function setup() {
const updateOne = jest.fn<() => Promise<unknown>>().mockResolvedValue({ matchedCount: 1 });
const findOneAndUpdate = jest.fn(() => ({ lean: () => ({ exec: async () => ({ anlageId: 'anlage', ...defaultSettings }) }) }));
const service = new VisualisierungService({ findOne: () => ({ exec: async () => ({ _id: 'anlage' }) }) } as any,
{ updateOne, findOneAndUpdate } as any);
return { service, updateOne, findOneAndUpdate };
}
it('legt anlagenbezogene Standardwerte beim ersten Laden an', async () => {
const { service, findOneAndUpdate } = setup();
expect(await service.get('anlage')).toEqual({ anlageId: 'anlage', ...defaultSettings });
expect(findOneAndUpdate).toHaveBeenCalledWith({ anlageId: 'anlage' }, { $setOnInsert: defaultSettings },
{ upsert: true, new: true, runValidators: true });
});
it('speichert Arbeitsflaeche, Ansicht und Snap getrennt pro Anlage', async () => {
const { service, updateOne } = setup();
const settings = { ...defaultSettings, snapToGrid: true, workspaceWidth: 4200, viewport: { x: -10, y: 20, width: 200, height: 100 } };
await service.save('anlage', settings);
expect(updateOne).toHaveBeenCalledWith({ anlageId: 'anlage' }, { $set: settings }, { upsert: true, runValidators: true });
});
it('verhindert Schreiben nach Anlagenwechsel', async () => {
const { service, updateOne } = setup();
await expect(service.save('andere', defaultSettings)).rejects.toThrow('Anlage');
expect(updateOne).not.toHaveBeenCalled();
});
it.each([{ workspaceWidth: 0 }, { gridStep: NaN }, { workspaceHeight: -1 }, { grid: 'true' },
{ viewport: { x: Infinity, y: 0, width: 10, height: 10 } }])('weist ungueltige Werte ab: %j', invalid => {
expect(() => validateSettings({ ...defaultSettings, ...invalid } as any)).toThrow();
});
});
@@ -0,0 +1,33 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Anlage } from '../_schemas/anlage.schema';
import type { VisualisierungSettings } from '../_schemas/anlagen/visualisierung-settings';
import { defaultSettings, validateSettings, type VisualisierungSettingsDto } from './visualisierung.dto';
@Injectable()
export class VisualisierungService {
constructor(@InjectModel(Anlage.name) private readonly anlagen: Model<Anlage>,
@InjectModel('VisualisierungSettings', 'anlagen') private readonly settings: Model<VisualisierungSettings>) {}
private async check(anlageId: string) {
const selected = await this.anlagen.findOne({ selected: true }).exec();
if (!selected || selected._id.toString() !== anlageId) throw new BadRequestException('Anlage geaendert. Visualisierung neu laden.');
}
async get(anlageId: string) {
await this.check(anlageId);
return this.settings.findOneAndUpdate({ anlageId }, { $setOnInsert: defaultSettings },
{ upsert: true, new: true, runValidators: true }).lean().exec();
}
async save(anlageId: string, dto: VisualisierungSettingsDto) {
validateSettings(dto); await this.check(anlageId);
// Nur Einstellwerte uebernehmen, keine vom Client gelieferten MongoDB-Felder.
const { workspaceWidth, workspaceHeight, grid, gridStep, snapToGrid, showHidden, selectedSpsAntriebId, viewport } = dto;
const { x, y, width, height } = viewport;
await this.settings.updateOne({ anlageId }, { $set: {
workspaceWidth, workspaceHeight, grid, gridStep, snapToGrid, showHidden, selectedSpsAntriebId,
viewport: { x, y, width, height },
} }, { upsert: true, runValidators: true });
return { success: true };
}
}
+24
View File
@@ -1,6 +1,17 @@
### Anlage 1659 --> 6995c44ebb286cf2c27da0d8 ### Anlage 1659 --> 6995c44ebb286cf2c27da0d8
### Test Group --> 6996c2cf14624b2583af43e9 ### Test Group --> 6996c2cf14624b2583af43e9
POST http://localhost:3000/draw/motor/render
Content-Type: application/json
{
"config": { "scale": 2, "raster": 4 },
"options": {
"colorInactive": "#808080",
"colorActive": "#00f000",
"colorError": "#f00000"
}
}
### Get All ### Get All
GET http://localhost:3000/draw/anlageDurmin GET http://localhost:3000/draw/anlageDurmin
@@ -62,3 +73,16 @@ GET http://localhost:3000/draw/behaelterMulti/svg
### motor ### motor
GET http://localhost:3000/draw/motor/svg GET http://localhost:3000/draw/motor/svg
### Motor: alle Zustände als SVG und XAML
POST http://localhost:3000/draw/motor/render
Content-Type: application/json
{
"config": { "scale": 2, "raster": 4 },
"options": {
"colorInactive": "#808080",
"colorActive": "#00f000",
"colorError": "#f00000"
}
}