diverse änderungen

This commit is contained in:
marco committed 2026-11-05 15:16:54 +01:00
1 parent 3dc1ad623c
commit f51631100d
85 files changed
+1879 -55

No files matched your search

+1
View File
@@ -58,3 +58,4 @@ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# OPC UA private keys and certificate store # OPC UA private keys and certificate store
/data/opcua/ /data/opcua/
/data/backups/ /data/backups/
/data/anlagen-pdf/
@@ -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>
@@ -1,16 +1,16 @@
<?xml version="1.0" ?> <?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="602" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="502" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="52" Height="602"> <Canvas Width="52" Height="502">
<Canvas> <Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin> <Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="581"/></TransformGroup></Canvas.RenderTransform> <Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="481"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,-580 v 600 h 40 v -600 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path> <Path Data="M 5,-480 v 500 h 40 v -500 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,-580 v 600 h 30 v -600 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path> <Path Data="M 10,-480 v 500 h 30 v -500 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 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> <Path Data="M 4,4 v 12 h 42 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas> </Canvas>
<Ellipse Canvas.Left="20" Canvas.Top="295" Width="12" Height="12" StrokeThickness="1" Stroke="#00f000" Fill="#00f000" ></Ellipse> <Ellipse Canvas.Left="20" Canvas.Top="245" Width="12" Height="12" StrokeThickness="1" Stroke="#00f000" Fill="#00f000" ></Ellipse>
</Canvas> </Canvas>
</Canvas> </Canvas>
</Viewbox> </Viewbox>
@@ -1,16 +1,16 @@
<?xml version="1.0" ?> <?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="602" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="502" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="52" Height="602"> <Canvas Width="52" Height="502">
<Canvas> <Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin> <Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="581"/></TransformGroup></Canvas.RenderTransform> <Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="481"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,-580 v 600 h 40 v -600 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path> <Path Data="M 5,-480 v 500 h 40 v -500 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,-580 v 600 h 30 v -600 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path> <Path Data="M 10,-480 v 500 h 30 v -500 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 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> <Path Data="M 4,4 v 12 h 42 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas> </Canvas>
<Ellipse Canvas.Left="20" Canvas.Top="295" Width="12" Height="12" StrokeThickness="1" Stroke="#f00000" Fill="#f00000" ></Ellipse> <Ellipse Canvas.Left="20" Canvas.Top="245" Width="12" Height="12" StrokeThickness="1" Stroke="#f00000" Fill="#f00000" ></Ellipse>
</Canvas> </Canvas>
</Canvas> </Canvas>
</Viewbox> </Viewbox>
@@ -1,12 +1,12 @@
<?xml version="1.0" ?> <?xml version="1.0" ?>
<Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="602" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Viewbox Stretch="None" StretchDirection="Both" Width="52" Height="502" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="52" Height="602"> <Canvas Width="52" Height="502">
<Canvas> <Canvas>
<Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin> <Canvas> <Canvas.RenderTransformOrigin>0.5,0.5</Canvas.RenderTransformOrigin>
<Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="581"/></TransformGroup></Canvas.RenderTransform> <Canvas.RenderTransform><TransformGroup> <TranslateTransform X="1" Y="481"/></TransformGroup></Canvas.RenderTransform>
<Path Data="M 5,-580 v 600 h 40 v -600 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path> <Path Data="M 5,-480 v 500 h 40 v -500 Z" StrokeThickness="2" Stroke="#404040" Fill="#404040" ></Path>
<Path Data="M 10,-580 v 600 h 30 v -600 Z" StrokeThickness="2" Stroke="#606060" Fill="#202020" ></Path> <Path Data="M 10,-480 v 500 h 30 v -500 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 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> <Path Data="M 4,4 v 12 h 42 v -12 Z" StrokeThickness="2" Stroke="#a0a0a0" Fill="#505050" ></Path>
</Canvas> </Canvas>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="13" Height="392">
<Canvas>
<Path Data="M 6,6 L 7,386" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 2.9789612916611725,378.01055398002836 L 7,386 L 10.978933590974023,377.98950142134595 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="171" Height="59">
<Canvas>
<Path Data="M 165,6 L 165,53 L 6,53" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 14,49 L 6,53 L 14,57 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="90" Height="70">
<Canvas>
<Path Data="M 1,1 L 89,1 L 89,69 L 1,69 Z" StrokeThickness="2" Stroke="#000000" Fill="#b3b3b3" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="90" Height="70">
<Canvas>
<Path Data="M 1,1 L 89,1 L 89,69 L 1,69 Z" StrokeThickness="2" Stroke="#000000" Fill="#b3b3b3" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="90" Height="70">
<Canvas>
<Path Data="M 1,1 L 89,1 L 89,69 L 1,69 Z" StrokeThickness="2" Stroke="#000000" Fill="#b3b3b3" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="12" Height="80">
<Canvas>
<Path Data="M 6,74 L 6,6" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 10,14 L 6,6 L 2,14 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="12" Height="81">
<Canvas>
<Path Data="M 6,6 L 6,75" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 2,67 L 6,75 L 10,67 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="12" Height="258">
<Canvas>
<Path Data="M 6,252 L 6,6" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 10,14 L 6,6 L 2,14 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="12" Height="310">
<Canvas>
<Path Data="M 6,6 L 6,304" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 2,296 L 6,304 L 10,296 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="66" Height="12">
<Canvas>
<Path Data="M 6,6 L 60,6" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 52,10 L 60,6 L 52,2 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="64" Height="12">
<Canvas>
<Path Data="M 58,6 L 6,6" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 14,2 L 6,6 L 14,10 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="68" Height="12">
<Canvas>
<Path Data="M 6,6 L 62,6" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 54,10 L 62,6 L 54,2 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,10 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="65" Height="12">
<Canvas>
<Path Data="M 59,6 L 6,6" StrokeThickness="3" Stroke="#00ff00" ></Path>
<Path Data="M 14,2 L 6,6 L 14,10 Z" StrokeThickness="1" Stroke="#00ff00" Fill="#00ff00" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="20" Height="40">
<Canvas>
<Path Data="M 4,31 Q 10 35 16 31" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 5.5,29 Q 10 32.5 14.5 29" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 7,27 Q 10 30 13 27" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 8,8 L 12,8 Q 13 8 13 9 L 13,24 Q 13 25 12 25 L 8,25 Q 7 25 7 24 L 7,9 Q 7 8 8 8 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#808080" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="40" Height="20">
<Canvas>
<Path Data="M 9,4 Q 5 10 9 16" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 11,5.5 Q 7.5 10 11 14.5" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 13,7 Q 10 10 13 13" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 32,8 L 32,12 Q 32 13 31 13 L 16,13 Q 15 13 15 12 L 15,8 Q 15 7 16 7 L 31,7 Q 32 7 32 8 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#808080" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="40" Height="20">
<Canvas>
<Path Data="M 31,16 Q 35 10 31 4" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 29,14.5 Q 32.5 10 29 5.5" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 27,13 Q 30 10 27 7" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 8,12 L 8,8 Q 8 7 9 7 L 24,7 Q 25 7 25 8 L 25,12 Q 25 13 24 13 L 9,13 Q 8 13 8 12 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#808080" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="20" Height="40">
<Canvas>
<Path Data="M 16,9 Q 10 5 4 9" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 14.5,11 Q 10 7.5 5.5 11" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 13,13 Q 10 10 7 13" StrokeThickness="1" Stroke="#808080" ></Path>
<Path Data="M 12,32 L 8,32 Q 7 32 7 31 L 7,16 Q 7 15 8 15 L 12,15 Q 13 15 13 16 L 13,31 Q 13 32 12 32 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#808080" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="20" Height="40">
<Canvas>
<Path Data="M 4,31 Q 10 35 16 31" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 5.5,29 Q 10 32.5 14.5 29" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 7,27 Q 10 30 13 27" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 8,8 L 12,8 Q 13 8 13 9 L 13,24 Q 13 25 12 25 L 8,25 Q 7 25 7 24 L 7,9 Q 7 8 8 8 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#00f000" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="40" Height="20">
<Canvas>
<Path Data="M 9,4 Q 5 10 9 16" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 11,5.5 Q 7.5 10 11 14.5" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 13,7 Q 10 10 13 13" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 32,8 L 32,12 Q 32 13 31 13 L 16,13 Q 15 13 15 12 L 15,8 Q 15 7 16 7 L 31,7 Q 32 7 32 8 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#00f000" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="40" Height="20">
<Canvas>
<Path Data="M 31,16 Q 35 10 31 4" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 29,14.5 Q 32.5 10 29 5.5" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 27,13 Q 30 10 27 7" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 8,12 L 8,8 Q 8 7 9 7 L 24,7 Q 25 7 25 8 L 25,12 Q 25 13 24 13 L 9,13 Q 8 13 8 12 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#00f000" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="20" Height="40">
<Canvas>
<Path Data="M 16,9 Q 10 5 4 9" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 14.5,11 Q 10 7.5 5.5 11" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 13,13 Q 10 10 7 13" StrokeThickness="1" Stroke="#00f000" ></Path>
<Path Data="M 12,32 L 8,32 Q 7 32 7 31 L 7,16 Q 7 15 8 15 L 12,15 Q 13 15 13 16 L 13,31 Q 13 32 12 32 Z" StrokeThickness="0.5" Stroke="#202020" Fill="#00f000" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0.5" Canvas.Top="0.5" Width="23" Height="23" StrokeThickness="1" Stroke="#000000" Fill="#00f000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0.5" Canvas.Top="0.5" Width="23" Height="23" StrokeThickness="1" Stroke="#000000" Fill="#808080" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="24" Height="24">
<Canvas>
<Ellipse Canvas.Left="0.5" Canvas.Top="0.5" Width="23" Height="23" StrokeThickness="1" Stroke="#000000" Fill="#ff0000" ></Ellipse>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="100" Height="100">
<Canvas>
<Path Data="M 0.5,0.5 L 99.5,0.5 L 99.5,99.5 L 0.5,99.5 Z" StrokeThickness="1" Stroke="#000000" Fill="#d1d1cc" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="100" Height="100">
<Canvas>
<Path Data="M 0.5,0.5 L 99.5,0.5 L 99.5,99.5 L 0.5,99.5 Z" StrokeThickness="1" Stroke="#000000" Fill="#d8eedf" ></Path>
</Canvas>
</Canvas>
</Viewbox>
@@ -0,0 +1,12 @@
<?xml version="1.0" ?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Canvas Width="30" Height="20">
<Canvas>
<Path Data="M 0.5,0.5 L 29.5,0.5 L 29.5,19.5 L 0.5,19.5 Z" StrokeThickness="1" Stroke="#000000" Fill="#0000ff" ></Path>
<Canvas>
<Grid Canvas.Left="5" Canvas.Top="5.833333333333333" Width="20" Height="8.333333333333334"><TextBlock Text="voll" FontFamily="Arial" FontSize="6.666666666666667" FontWeight="Bold" Foreground="#ffffff" HorizontalAlignment="Center" VerticalAlignment="Center"/></Grid>
</Canvas>
</Canvas>
</Canvas>
</Viewbox>
+30
View File
@@ -0,0 +1,30 @@
# Anlagen-PDF
Unter **Anlage → Anlagen-PDF** wird eine PDF für die aktuell ausgewählte Anlage hinterlegt (maximal 100 MB). In der Unit-Bearbeitung öffnet **Im PDF öffnen** dieselbe Ansicht mit ausgewählter Unit.
Die Ansicht liest den Text aller Seiten mit PDF.js im Browser ein. Nach Abschluss der Indexierung kann nach Namen oder vollständigen EPLAN-Verweisen gesucht werden. Eine Unit verwendet zunächst die Verweise aus ihren Signalbeschreibungen und zugeordneten IOs (`seiteName`, `functionText`). Beispiel: `102 · =BAI-ET+29/5` verweist auf Struktur `=BAI-ET+29`, EPLAN-Seite `5`. Die Zahl `102` wird nicht als PDF-Seitennummer interpretiert. Die Suche berücksichtigt die vollständige Kennung und unterscheidet `/5`, `/50` und `/5.1`. PDF-Seitenlabels werden ebenfalls berücksichtigt.
Bei einem eindeutigen Treffer wird die PDF-Seite geöffnet. Mehrere Treffer, etwa durch Querverweise auf anderen Blättern, werden zur Auswahl angezeigt. Ohne passenden EPLAN-Treffer wird nach dem Unit-Namen gesucht. **Seite dieser Unit zuordnen** speichert eine manuelle Zuordnung mit Vorrang vor der Suche. Reine Scans benötigen diese manuelle Zuordnung; OCR ist nicht enthalten.
Beim Ersetzen der PDF werden manuelle Zuordnungen zurückgesetzt. Zuordnungsänderungen enthalten die PDF-Version; Änderungen aus einer veralteten Ansicht werden abgelehnt. Die Original-Units werden nicht verändert, ihre Kopien erhalten keine manuelle Seitenzuordnung.
## Speicherung und API
- Binärdateien: `rk-backend/data/anlagen-pdf/<Anlagen-ID>/<Version>.pdf`
- Metadaten und manuelle Zuordnungen: MongoDB `rk2.anlage_pdfs`
- PDF-Dateien separat sichern; die bestehende MongoDB-Sicherung umfasst die Metadaten, keine Dateien im Dateisystem.
- `GET /anlage/:id/pdf`: Metadaten oder `null`
- `POST /anlage/:id/pdf`: Multipart-Feld `file`, PDF hochladen/ersetzen
- `GET /anlage/:id/pdf/file?version=…`: PDF, einschließlich Byte-Range-Unterstützung
- `GET /anlage/:id/pdf/units`: Units der Anlage mit EPLAN-Verweisen
- `PATCH /anlage/:id/pdf/units/:unitId`: `{ version, page }`, `page: null` entfernt die Zuordnung
Das Frontend leitet diese Aufrufe über `/api/anlagen/:id/pdf` an das Backend weiter. Worker, Schriftarten, CMaps und WASM-Dateien stammen aus dem installierten `pdfjs-dist` und werden über `/api/pdf-assets` lokal ausgeliefert. Es werden keine externen PDF-Dienste verwendet.
## Prüfung
Backend: `npm test -- --runInBand --config test/anlage-pdf-jest.json`
Frontend-Suchlogik (Node 22): `node --experimental-strip-types --test src/lib/pdf-search.test.ts`
Zusätzlich in beiden Projekten `npm run build` ausführen. Mit einer echten EPLAN-PDF die Erkennung des Schriftfelds und die Suche nach `=BAI-ET+29/5` prüfen; Textreihenfolge und Zeichencodierung hängen vom PDF-Export ab.
+5 -1
View File
@@ -8,7 +8,11 @@ GET/PUT /rk2/parameter; GET /rk2/parameter/export. Frontend /parameter und /para
Export: AllgemeineAnlageParameter.xlsx, Tabellenblatt AllgemeineAnlageParameter, acht Spalten der Vorlage. Anzahl nur bei Nummer 0, alle Nummern 0 bis Anzahl-1 inklusive freier Zeilen. Zahlen bleiben Zahlen; leere Zahlenfelder bleiben leer. Skalierung wird als Konfiguration exportiert, Werte werden dabei nicht multipliziert. Export: AllgemeineAnlageParameter.xlsx, Tabellenblatt AllgemeineAnlageParameter, acht Spalten der Vorlage. Anzahl nur bei Nummer 0, alle Nummern 0 bis Anzahl-1 inklusive freier Zeilen. Zahlen bleiben Zahlen; leere Zahlenfelder bleiben leer. Skalierung wird als Konfiguration exportiert, Werte werden dabei nicht multipliziert.
Min darf Max nicht uebersteigen. Startwerte ausserhalb des Bereichs werden im Frontend angezeigt, aber entsprechend der Beispielvorlage nicht blockiert. Zahlen muessen endlich sein. ProCon-Vergleich und bidirektionale Synchronisierung pro gespeicherter Zeile ueber /rk2/parameter/:id/sync (GET/POST). ParameterTyp, Kategorie=13, Nummer=Parameter-Nr. Beschreibung=Text, Min=Minimum, Max=Maximum, Startwert=DefaultWert, Wertigkeit=Einheit, SPS-Skalierung=Skalierung. Laufende Werte in Parameter.Wert bleiben unveraendert. Fehlende oder doppelte Nummern blockieren den Abgleich; fehlende Zeilen zuerst per Excel in ProCon importieren. Vergleichsversion, lokale Revision und aktive Verbindung werden geprueft; SQL-Updates erfolgen parametrisiert und transaktional mit Pruefung der alten Werte. ProCon-Skalierung ist ein SQL-Int; Nachkommazahlen werden dafuer abgelehnt. **Wert (MongoDB)** ist ein eigener, bearbeitbarer Wert pro Anlagenparameter. Speichern schreibt ihn mit Revisionskontrolle in allgemeine_anlageparameter. Bestehende Datensaetze ohne wert bleiben leer; es erfolgt keine automatische Uebernahme. Startwert (DefaultWert) ist davon unabhaengig. Leeren speichert null, 0 bleibt ein echter Wert.
**Wert (ProCon)** zeigt eine lesbare Momentaufnahme von Parameter.Wert. Der Einzel- und Sammelvergleich umfasst den Wert zusammen mit den sechs Definitionsfeldern. Aus ProCon uebernehmen speichert alles lokal; nach ProCon uebernehmen schreibt Definition und Wert gemeinsam in einer SQL-Transaktion. Nur eindeutig vorhandene Parameterinstanzen sind synchronisierbar. Datentyp, Min/Max, Vergleichsversion und zwischenzeitliche Aenderungen werden geprueft. Numerische Dezimalkommas werden fuer ProCon normalisiert. Der Excel-Export bleibt bei den acht Definitionsspalten.
Min darf Max nicht uebersteigen. Startwerte ausserhalb des Bereichs werden im Frontend angezeigt, aber entsprechend der Beispielvorlage nicht blockiert. Zahlen muessen endlich sein. ProCon-Vergleich und bidirektionale Synchronisierung pro gespeicherter Zeile ueber /rk2/parameter/:id/sync (GET/POST). ParameterTyp, Kategorie=13, Nummer=Parameter-Nr. Beschreibung=Text, Min=Minimum, Max=Maximum, Startwert=DefaultWert, Wertigkeit=Einheit, SPS-Skalierung=Skalierung. Der lokale Wert wird mit Parameter.Wert abgeglichen. Fehlende oder doppelte Nummern blockieren den Abgleich; fehlende Zeilen zuerst per Excel in ProCon importieren. Vergleichsversion, lokale Revision und aktive Verbindung werden geprueft; SQL-Updates erfolgen parametrisiert und transaktional mit Pruefung der alten Werte. ProCon-Skalierung ist ein SQL-Int; Nachkommazahlen werden dafuer abgelehnt.
## ProCon-Parameter zurücksetzen ## ProCon-Parameter zurücksetzen
+4
View File
@@ -31,6 +31,10 @@ export class DrawDataDto {
} }
export class DrawShapeOptionenDto{ export class DrawShapeOptionenDto{
text?: string;
fontSize?: number;
frame?: boolean;
direction?: 'oben' | 'unten' | 'rechts' | 'links';
stroke?:string; stroke?:string;
strokeWidth?:number; strokeWidth?:number;
fill?:string; fill?:string;
+20
View File
@@ -0,0 +1,20 @@
import { BadRequestException } from '@nestjs/common';
import { parseMotorRequest } from './motor.dto';
import type { EndschalterDirection } from '../graphics/elements/types';
export function parseEndschalterRequest(input: unknown) {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
throw new BadRequestException('Erwartet werden config und optional options');
}
const request = input as Record<string, unknown>;
const options = request.options === undefined ? {} : request.options;
if (typeof options !== 'object' || options === null || Array.isArray(options)) {
throw new BadRequestException('Endschalter-options muss ein Objekt sein');
}
const { direction = 'unten', ...colors } = options as Record<string, unknown>;
if (typeof direction !== 'string' || !['oben', 'unten', 'rechts', 'links'].includes(direction)) {
throw new BadRequestException('direction muss oben, unten, rechts oder links sein');
}
const parsed = parseMotorRequest({ ...request, options: colors });
return { config: parsed.config, options: { ...parsed.options, direction: direction as EndschalterDirection } };
}
+43
View File
@@ -0,0 +1,43 @@
import { BadRequestException } from '@nestjs/common';
import type { TextConfig, TextOptions } from '../graphics/elements/types';
import { parseMotorRequest } from './motor.dto';
import { parseRechteckRequest } from './rechteck.dto';
export function parseTextRequest(input: unknown): { config: TextConfig; options: TextOptions } {
const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
if (!isObject(input) || !isObject(input.config) || Object.keys(input).some(key => !['config', 'options'].includes(key))) {
throw new BadRequestException('Text erwartet config und optional options.');
}
const config = input.config;
if (Object.keys(config).some(key => !['text', 'width', 'height', 'fontSize'].includes(key))) {
throw new BadRequestException('Text-config erlaubt text, width, height und fontSize.');
}
const text = config.text ?? 'Text';
const fontSize = config.fontSize ?? 16;
if (typeof text !== 'string' || text.length > 2000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) {
throw new BadRequestException('Text muss eine Zeichenfolge mit maximal 2000 Zeichen sein.');
}
if (typeof fontSize !== 'number' || !Number.isFinite(fontSize) || fontSize <= 0) {
throw new BadRequestException('Schriftgröße muss eine positive endliche Zahl sein.');
}
const options = input.options === undefined ? {} : input.options;
const allowed = ['frame', 'stroke', 'strokeWidth', 'fill', 'colorInactive', 'colorActive', 'colorError'];
if (!isObject(options) || Object.keys(options).some(key => !allowed.includes(key))) {
throw new BadRequestException('Ungültige Text-options.');
}
const frame = options.frame ?? false;
if (typeof frame !== 'boolean') throw new BadRequestException('frame muss true oder false sein.');
const rectangle = parseRechteckRequest({
config: { width: config.width ?? 120, height: config.height ?? 40 },
options: { stroke: options.stroke ?? '#000000', strokeWidth: options.strokeWidth ?? 1, fill: options.fill ?? 'transparent' },
});
const colors = parseMotorRequest({ config: {}, options: {
colorInactive: options.colorInactive ?? '#808080', colorActive: options.colorActive ?? '#00f000', colorError: options.colorError ?? '#f00000',
} }).options!;
return {
config: { text, fontSize, ...rectangle.config },
options: { ...rectangle.options, ...colors, frame,
strokeWidth: frame ? rectangle.options.strokeWidth : 0 } as TextOptions,
};
}
@@ -77,7 +77,7 @@ const elemente = ProConViewAggregateSchema.path<MongooseSchema.Types.DocumentArr
elemente.discriminator('xaml', new MongooseSchema({ elemente.discriminator('xaml', new MongooseSchema({
generator: { generator: {
type: new MongooseSchema({ type: new MongooseSchema({
grafikTyp: { type: String, enum: ['motor', 'punkt', 'rechteck', 'bandOben', 'warnung', 'pfeil', 'anlageDurmin', 'fahrwagenOben', 'fahrbandOben'], required: true }, grafikTyp: { type: String, enum: ['motor', 'endschalter', 'text', 'punkt', 'rechteck', 'bandOben', 'warnung', 'pfeil', 'anlageDurmin', 'fahrwagenOben', 'fahrbandOben'], required: true },
config: { type: MongooseSchema.Types.Mixed, required: true }, config: { type: MongooseSchema.Types.Mixed, required: true },
options: { type: MongooseSchema.Types.Mixed, default: () => ({}) }, options: { type: MongooseSchema.Types.Mixed, default: () => ({}) },
ergebnis: { type: MongooseSchema.Types.Mixed }, ergebnis: { type: MongooseSchema.Types.Mixed },
@@ -81,9 +81,26 @@ describe('Anzeigewerte-Synchronisierung', () => {
await expect(service.apply('row1', { ...request, fields: true })).rejects.toThrow('numerische ProCon-ID'); await expect(service.apply('row1', { ...request, fields: true })).rejects.toThrow('numerische ProCon-ID');
expect(updateComparedRow).not.toHaveBeenCalled(); expect(updateComparedRow).not.toHaveBeenCalled();
}); });
it('rollt bei gemeinsam verwendeten Views alle SQL-Änderungen zurück', async () => { it('aktualisiert gemeinsam verwendete Views unabhängig von der Anzahl ihrer Verwendungen', async () => {
data.views[0].Verwendungen = 42;
await service.apply('row1', { ...request, graphics: true });
expect(updateComparedRow).toHaveBeenCalledWith(transaction, 'Views', 'Ein.xaml',
{ Data: Buffer.from('<Viewbox/>').toString('base64') }, data.views[0]);
expect(transaction.commit).toHaveBeenCalled(); expect(transaction.rollback).not.toHaveBeenCalled();
});
it('schreibt identische Grafiken für dieselbe View nur einmal', async () => {
data.views[0].Verwendungen = 2; data.views[0].Verwendungen = 2;
await expect(service.apply('row1', { ...request, graphics: true })).rejects.toThrow('mehrfach'); data.row.graphics.push({ ...structuredClone(data.row.graphics[0]), slot: 'aus' });
data.visuals.push({ ...data.visuals[0], Id: 12, State: 1 });
await service.apply('row1', { ...request, layout: false, graphics: true });
const writes = (updateComparedRow as any).mock.calls.filter((call: any[]) => call[1] === 'Views');
expect(writes).toHaveLength(1);
expect(transaction.commit).toHaveBeenCalled();
});
it('rollt widersprüchliche Grafiken für dieselbe View weiterhin zurück', async () => {
data.row.graphics.push({ ...structuredClone(data.row.graphics[0]), slot: 'aus', xamlOverride: '<Viewbox><Canvas/></Viewbox>' });
data.visuals.push({ ...data.visuals[0], Id: 12, State: 1 });
await expect(service.apply('row1', { ...request, graphics: true })).rejects.toThrow('Unterschiedliche Grafiken');
expect(transaction.rollback).toHaveBeenCalled(); expect(transaction.commit).not.toHaveBeenCalled(); expect(transaction.rollback).toHaveBeenCalled(); expect(transaction.commit).not.toHaveBeenCalled();
}); });
it('schreibt XAML als Base64 und prüft die Visualisierungszuordnung auch ohne Layoutänderung', async () => { it('schreibt XAML als Base64 und prüft die Visualisierungszuordnung auch ohne Layoutänderung', async () => {
@@ -144,10 +144,7 @@ export class DisplaySyncService {
const view = data.views.find(view => view.Id === remote.ViewId); const view = data.views.find(view => view.Id === remote.ViewId);
const variant = graphic.generator.ergebnis?.varianten.find(variant => variant.state === graphic.variant); const variant = graphic.generator.ergebnis?.varianten.find(variant => variant.state === graphic.variant);
if (!view || !variant?.xaml) throw new BadRequestException('Lokale oder zugeordnete ProCon-Grafik fehlt'); if (!view || !variant?.xaml) throw new BadRequestException('Lokale oder zugeordnete ProCon-Grafik fehlt');
if (Number(view.Verwendungen) > 1) throw new BadRequestException('XAML wird mehrfach in ProCon verwendet. Zuerst eine eigene View zuweisen.'); // Die View wird bewusst gemeinsam aktualisiert; alle Verwendungen erhalten dasselbe XAML.
const usage = await new sql.Request(transaction).input('viewId', sql.NVarChar(255), view.Id)
.query('SELECT (SELECT COUNT(*) FROM Visualisierungen WHERE ViewId=@viewId) + (SELECT COUNT(*) FROM Komponenten WHERE ViewId=@viewId) AS Anzahl');
if (Number(usage.recordset[0]?.Anzahl) !== 1) throw new BadRequestException('XAML-Zuordnung inzwischen geändert oder mehrfach verwendet');
const xaml = graphic.xamlOverride ?? variant.xaml; validateSyncXml(xaml); const xaml = graphic.xamlOverride ?? variant.xaml; validateSyncXml(xaml);
if (writtenViews.has(view.Id)) { if (writtenViews.has(view.Id)) {
if (writtenViews.get(view.Id) !== xaml) throw new BadRequestException('Unterschiedliche Grafiken verwenden dieselbe View'); if (writtenViews.get(view.Id) !== xaml) throw new BadRequestException('Unterschiedliche Grafiken verwenden dieselbe View');
@@ -11,7 +11,7 @@ export class DisplayController {
@Get() get() { return this.displays.get(); } @Get() get() { return this.displays.get(); }
@Put() save(@Body() body: DisplayTable) { return this.displays.save(body); } @Put() save(@Body() body: DisplayTable) { return this.displays.save(body); }
@Get('export') async excel() { return new StreamableFile(createDisplayExcel(await this.displays.get()), { @Get('export') async excel() { return new StreamableFile(createDisplayExcel(await this.displays.get()), {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', disposition: 'attachment; filename="Anzeigewerte.xlsx"', type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', disposition: 'attachment; filename="AllgemeinAnlagenVisualisierung.xlsx"',
}); } }); }
@Get('xaml') xaml() { return this.displays.xamlFiles(); } @Get('xaml') xaml() { return this.displays.xamlFiles(); }
@Post('xaml') exportXaml(@Body() dto: { anlageId: string }) { return this.displays.exportXaml(dto?.anlageId); } @Post('xaml') exportXaml(@Body() dto: { anlageId: string }) { return this.displays.exportXaml(dto?.anlageId); }
@@ -0,0 +1,86 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
jest.mock('./parameter.service', () => ({ ParameterService: class {} }));
jest.mock('../../infrastructure/sql/sql.service', () => ({ SqlService: class {} }));
jest.mock('../../visualisierung/shared/procon-sync', () => ({ updateComparedRow: jest.fn<() => Promise<void>>() }));
jest.mock('mssql', () => ({ ...jest.requireActual('mssql') as object, Transaction: jest.fn(), Request: jest.fn() }));
import * as sql from 'mssql';
import { ParameterSyncService, type ParameterBulkSyncRequest } from './parameter-sync.service';
import { updateComparedRow } from '../../visualisierung/shared/procon-sync';
describe('Parameter-Sammelabgleich', () => {
let service: ParameterSyncService, data: any, parameters: any, transaction: any, query: any;
const request: ParameterBulkSyncRequest = { anlageId: 'a', verbindungId: 'v', version: 'hash', direction: 'toProcon', ids: ['p0', 'p1'] };
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(updateComparedRow).mockReset().mockResolvedValue(undefined);
const rows = [0, 1, 2].map(nr => ({ id: `p${nr}`, parameterNr: nr, beschreibung: `Lokal ${nr}`, min: 0, max: 100,
wert: '12', startwert: 10, wertigkeit: 's', skalierungSps: 1000 }));
const remote = [0, 1, 3].map(nr => ({ Wert: '0', ParameterId: nr + 70, WertAnzahl: 1, TypeString: 'System.Int32', Id: nr + 40, Nummer: nr, Kategorie: 13, Text: `Remote ${nr}`,
Minimum: '1,5', Maximum: '99', DefaultWert: null, Einheit: 'kg', Skalierung: 1 }));
data = { anlageId: 'a', verbindungId: 'v', version: 'hash', pool: {}, remote,
table: { anlageId: 'a', version: 2, reservedCount: 40, rows } };
parameters = { get: jest.fn(async () => data.table), save: jest.fn(async (table: any) => table) };
service = new ParameterSyncService(parameters, {} as any, {} as any);
jest.spyOn(service as any, 'loadAll').mockImplementation(async () => data);
jest.spyOn(service as any, 'context').mockResolvedValue({ anlageId: 'a', verbindungId: 'v' });
transaction = { begin: jest.fn(async () => undefined), commit: jest.fn(async () => undefined), rollback: jest.fn(async () => undefined) };
(sql.Transaction as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => transaction);
query = { input: jest.fn(() => query), query: jest.fn(async (statement: string) => ({ recordset: statement.includes('SELECT Id,Wert') ? [{ Id: query.definitionId - 40 + 70, Wert: '0' }] : data.remote })) };
query.input.mockImplementation((name: string, type: unknown, value: number) => { query.definitionId = value; return query; });
(sql.Request as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => query);
});
it('zeigt Unterschiede sowie nur lokal oder nur in ProCon vorhandene Nummern', async () => {
const comparison = await service.compareAll();
expect(comparison.rows.map(row => row.status)).toEqual(['Unterschiede', 'Unterschiede', 'Nur MongoDB', 'Nur ProCon']);
expect(comparison.rows.map(row => row.selectable)).toEqual([true, true, false, false]);
expect(comparison.rows[0].differences).toContain('min');
data.table.rows[0] = { ...data.table.rows[0], beschreibung: 'Remote 0', min: 1.5, max: 99, wert: '0', startwert: null, wertigkeit: 'kg', skalierungSps: 1 };
expect((await service.compareAll()).rows[0].status).toBe('Gleich');
});
it('sperrt doppelte Nummern und ungültige ProCon-Zahlen', async () => {
data.remote.push({ ...data.remote[0], Id: 90 });
data.remote[1].Minimum = 'keine Zahl';
const comparison = await service.compareAll();
expect(comparison.rows[0].selectable).toBe(false);
expect(comparison.rows[1].selectable).toBe(false);
await expect(service.applyAll(request)).rejects.toThrow('nicht eindeutig');
expect(transaction.begin).not.toHaveBeenCalled();
});
it('übernimmt nur ausgewählte ProCon-Werte mit einer einzigen lokalen Speicherung', async () => {
const result = await service.applyAll({ ...request, direction: 'toLocal' });
expect(parameters.save).toHaveBeenCalledTimes(1);
expect(result.rows[0]).toMatchObject({ id: 'p0', parameterNr: 0, beschreibung: 'Remote 0', min: 1.5, startwert: null });
expect(result.rows[1].beschreibung).toBe('Remote 1');
expect(result.rows[2]).toBe(data.table.rows[2]);
expect(transaction.begin).not.toHaveBeenCalled();
});
it('schreibt die SQL-Auswahl gemeinsam und prüft den gelesenen Stand unter Sperre', async () => {
await service.applyAll(request);
expect(query.query).toHaveBeenCalledWith(expect.stringContaining('WITH (UPDLOCK,HOLDLOCK) WHERE Kategorie=13'));
expect(updateComparedRow).toHaveBeenCalledTimes(4);
expect(updateComparedRow).toHaveBeenCalledWith(transaction, 'ParameterTyp', 40,
expect.objectContaining({ Kategorie: 13, Nummer: 0, Text: 'Lokal 0', Minimum: '0', Skalierung: 1000 }), data.remote[0]);
expect(transaction.commit).toHaveBeenCalledTimes(1);
expect(parameters.save).not.toHaveBeenCalled();
});
it('rollt bei geändertem SQL-Stand oder einem Schreibfehler die gesamte Auswahl zurück', async () => {
query.query.mockResolvedValueOnce({ recordset: [] });
await expect(service.applyAll(request)).rejects.toThrow('inzwischen geändert');
expect(transaction.rollback).toHaveBeenCalledTimes(1);
expect(updateComparedRow).not.toHaveBeenCalled();
jest.mocked(updateComparedRow).mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('Schreibkonflikt'));
await expect(service.applyAll(request)).rejects.toThrow('Schreibkonflikt');
expect(transaction.rollback).toHaveBeenCalledTimes(2);
expect(transaction.commit).not.toHaveBeenCalled();
});
it('weist veraltete Vergleiche, ungültige Auswahl und ungeeignete SQL-Skalierung vor dem Schreiben ab', async () => {
for (const patch of [{ version: 'alt' }, { anlageId: 'andere' }, { ids: [] }, { ids: ['p0', 'p0'] }, { ids: ['p2'] }]) {
await expect(service.applyAll({ ...request, ...patch })).rejects.toThrow();
}
data.table.rows[1].skalierungSps = 1.5;
await expect(service.applyAll(request)).rejects.toThrow('SPS-Skalierung');
expect(transaction.begin).not.toHaveBeenCalled();
expect(parameters.save).not.toHaveBeenCalled();
});
});
+194 -3
View File
@@ -7,7 +7,34 @@ import { Anlage } from '../../_schemas/anlage.schema';
import { SqlService } from '../../infrastructure/sql/sql.service'; import { SqlService } from '../../infrastructure/sql/sql.service';
import { updateComparedRow } from '../../visualisierung/shared/procon-sync'; import { updateComparedRow } from '../../visualisierung/shared/procon-sync';
import { ParameterService } from './parameter.service'; import { ParameterService } from './parameter.service';
import type { ParameterRow } from './parameter.dto';
import { validateParameterValue } from '../element-parameter/element-parameter.dto';
export interface ProconParameterValueRequest {
anlageId: string; verbindungId: string; parameterId: number; version: string; wert: string | null;
}
interface ProconValue extends Record<string, unknown> {
parameterNr: number; definitionId: number; parameterId: number | null; wert: string | null;
dataType: string | null; minimum: string | null; maximum: string | null;
}
const valueColumns = `t.Nummer AS parameterNr,t.Id AS definitionId,p.Id AS parameterId,p.Wert AS wert,
t.TypeString AS dataType,t.Minimum AS minimum,t.Maximum AS maximum`;
export interface ParameterSyncRequest { anlageId: string; verbindungId: string; version: string; direction: 'toLocal' | 'toProcon' } export interface ParameterSyncRequest { anlageId: string; verbindungId: string; version: string; direction: 'toLocal' | 'toProcon' }
export interface ParameterBulkSyncRequest extends ParameterSyncRequest { ids: string[] }
export interface RemoteParameter extends Record<string, unknown> {
Wert: string | null; ParameterId: number | null; WertAnzahl: number; TypeString: string | null;
Id: number; Nummer: number; Kategorie: number; Text: string | null; Minimum: string | null;
Maximum: string | null; DefaultWert: string | null; Einheit: string | null; Skalierung: number | null;
}
const snapshotColumns = `Id,Nummer,Kategorie,Text,Minimum,Maximum,DefaultWert,Einheit,Skalierung,TypeString,
(SELECT COUNT(*) FROM Parameter p WHERE p.ParameterTypId=ParameterTyp.Id) AS WertAnzahl,
(SELECT MIN(p.Id) FROM Parameter p WHERE p.ParameterTypId=ParameterTyp.Id) AS ParameterId,
(SELECT MAX(p.Wert) FROM Parameter p WHERE p.ParameterTypId=ParameterTyp.Id) AS Wert`;
const comparedFields = ['wert', 'beschreibung', 'min', 'max', 'startwert', 'wertigkeit', 'skalierungSps'] as const;
function remoteValues(remote: RemoteParameter) {
return { wert: remote.Wert ?? null, beschreibung: remote.Text ?? '', min: parseProconNumber(remote.Minimum), max: parseProconNumber(remote.Maximum),
startwert: parseProconNumber(remote.DefaultWert), wertigkeit: remote.Einheit ?? '', skalierungSps: parseProconNumber(remote.Skalierung) };
}
export function parseProconNumber(value: unknown): number | null { export function parseProconNumber(value: unknown): number | null {
if (value === null || value === undefined || typeof value === 'string' && !value.trim()) return null; if (value === null || value === undefined || typeof value === 'string' && !value.trim()) return null;
const normalized = typeof value === 'string' ? value.trim().replace(',', '.') : value; const normalized = typeof value === 'string' ? value.trim().replace(',', '.') : value;
@@ -25,6 +52,54 @@ export class ParameterSyncService {
if (!selected?.aktiveProConVerbindungId) throw new BadRequestException('Aktive ProCon-Verbindung fehlt'); if (!selected?.aktiveProConVerbindungId) throw new BadRequestException('Aktive ProCon-Verbindung fehlt');
return { anlageId: selected._id.toString(), verbindungId: selected.aktiveProConVerbindungId }; return { anlageId: selected._id.toString(), verbindungId: selected.aktiveProConVerbindungId };
} }
async proconValues() {
const context = await this.context();
const pool = await this.db.getPool(context.anlageId);
const rows = (await pool.request().query(`SELECT ${valueColumns} FROM ParameterTyp t
LEFT JOIN Parameter p ON p.ParameterTypId=t.Id
WHERE t.Kategorie=13 ORDER BY t.Nummer,t.Id,p.Id`)).recordset as ProconValue[];
if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung geändert.');
return { ...context, readAt: new Date().toISOString(), values: rows.map(row => ({ ...row, version: this.valueVersion(context, row) })) };
}
private valueVersion(context: { anlageId: string; verbindungId: string }, row: ProconValue) {
return createHash('sha256').update(JSON.stringify({ context, parameterId: row.parameterId, definitionId: row.definitionId,
parameterNr: row.parameterNr, wert: row.wert, dataType: row.dataType, minimum: row.minimum, maximum: row.maximum })).digest('hex');
}
async setProconValue(dto: ProconParameterValueRequest) {
if (!dto || !Number.isSafeInteger(dto.parameterId) || dto.parameterId < 1 || typeof dto.version !== 'string'
|| (dto.wert !== null && (typeof dto.wert !== 'string' || dto.wert.length > 10000))) {
throw new BadRequestException('Ungültiger Parameterwert oder ProCon-Parameter-ID.');
}
const context = await this.context();
if (dto.anlageId !== context.anlageId || dto.verbindungId !== context.verbindungId) throw new BadRequestException('Anlage oder Verbindung geändert.');
const pool = await this.db.getPool(context.anlageId);
const transaction = new sql.Transaction(pool);
await transaction.begin(sql.ISOLATION_LEVEL.SERIALIZABLE);
try {
const rows = (await new sql.Request(transaction).input('id', sql.Int, dto.parameterId).query(`SELECT ${valueColumns}
FROM Parameter p WITH (UPDLOCK,HOLDLOCK) INNER JOIN ParameterTyp t WITH (HOLDLOCK) ON t.Id=p.ParameterTypId
WHERE t.Kategorie=13 AND p.Id=@id`)).recordset as ProconValue[];
if (rows.length !== 1) throw new BadRequestException('Allgemeiner ProCon-Parameter nicht mehr vorhanden.');
const row = rows[0];
if (this.valueVersion(context, row) !== dto.version) throw new BadRequestException('Wert oder Parameterdefinition inzwischen geändert. ProCon-Werte neu laden.');
validateParameterValue(dto.wert, row.dataType ?? '');
let wert = dto.wert;
if (wert !== null && ['System.Double', 'System.Int32'].includes(row.dataType ?? '')) {
wert = wert.trim().replace(',', '.');
const numeric = Number(wert);
const minimum = parseProconNumber(row.minimum), maximum = parseProconNumber(row.maximum);
if (minimum !== null && numeric < minimum || maximum !== null && numeric > maximum) {
throw new BadRequestException(`Wert muss innerhalb Min ${minimum ?? 'offen'} und Max ${maximum ?? 'offen'} liegen.`);
}
}
await updateComparedRow(transaction, 'Parameter', dto.parameterId, { Wert: wert, ParameterTypId: row.definitionId },
{ Wert: row.wert, ParameterTypId: row.definitionId });
if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung inzwischen geändert.');
await transaction.commit();
return { parameterId: dto.parameterId, wert };
} catch (cause) { await transaction.rollback().catch(() => undefined); throw cause; }
}
private async load(id: string) { private async load(id: string) {
const context = await this.context(), table = await this.parameters.get(); const context = await this.context(), table = await this.parameters.get();
if (table.anlageId !== context.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.'); if (table.anlageId !== context.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.');
@@ -32,9 +107,10 @@ export class ParameterSyncService {
if (!row) throw new BadRequestException('Parameter nicht mehr vorhanden'); if (!row) throw new BadRequestException('Parameter nicht mehr vorhanden');
const pool = await this.db.getPool(context.anlageId); const pool = await this.db.getPool(context.anlageId);
const matches = (await pool.request().input('nr', sql.Int, row.parameterNr).query( const matches = (await pool.request().input('nr', sql.Int, row.parameterNr).query(
'SELECT Id,Nummer,Kategorie,Text,Minimum,Maximum,DefaultWert,Einheit,Skalierung FROM ParameterTyp WHERE Kategorie=13 AND Nummer=@nr')).recordset; `SELECT ${snapshotColumns} FROM ParameterTyp WHERE Kategorie=13 AND Nummer=@nr`)).recordset;
if (matches.length !== 1) throw new BadRequestException('Parameter-Nr. fehlt in ProCon oder ist mehrfach vorhanden. Zuerst Excel in ProCon importieren bzw. Zuordnung korrigieren.'); if (matches.length !== 1) throw new BadRequestException('Parameter-Nr. fehlt in ProCon oder ist mehrfach vorhanden. Zuerst Excel in ProCon importieren bzw. Zuordnung korrigieren.');
const remote = matches[0]; const remote = matches[0] as RemoteParameter;
if (remote.WertAnzahl !== 1) throw new BadRequestException('ProCon-Parameterwert fehlt oder ist mehrfach vorhanden.');
if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung geändert'); if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung geändert');
const version = createHash('sha256').update(JSON.stringify({ context, revision: table.version, row, remote })).digest('hex'); const version = createHash('sha256').update(JSON.stringify({ context, revision: table.version, row, remote })).digest('hex');
return { ...context, table, row, remote, pool, version }; return { ...context, table, row, remote, pool, version };
@@ -59,6 +135,120 @@ export class ParameterSyncService {
const data = await this.load(id); const data = await this.load(id);
return { anlageId: data.anlageId, verbindungId: data.verbindungId, version: data.version, local: data.row, remote: data.remote }; return { anlageId: data.anlageId, verbindungId: data.verbindungId, version: data.version, local: data.row, remote: data.remote };
} }
private async loadAll() {
const context = await this.context();
const table = await this.parameters.get();
if (table.anlageId !== context.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.');
const pool = await this.db.getPool(context.anlageId);
const remote = (await pool.request().query(
`SELECT ${snapshotColumns} FROM ParameterTyp WHERE Kategorie=13 ORDER BY Nummer,Id`)).recordset as RemoteParameter[];
if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung geändert');
const version = createHash('sha256').update(JSON.stringify({ context, table, remote })).digest('hex');
return { ...context, table, remote, pool, version };
}
private comparisonRows(data: Awaited<ReturnType<ParameterSyncService['loadAll']>>) {
const localNumbers = new Set(data.table.rows.map(row => row.parameterNr));
const compare = (local: ParameterRow | null, remote: RemoteParameter | null, ambiguous: boolean) => {
let issue = ambiguous ? 'Parameternummer ist mehrfach vorhanden.' : remote && remote.WertAnzahl !== 1 ? 'ProCon-Parameterwert fehlt oder ist mehrfach vorhanden.' : '';
let differences: string[] = [];
if (local && remote && !ambiguous) {
try {
const values = remoteValues(remote);
differences = comparedFields.filter(field => (local[field] ?? null) !== values[field]);
} catch { issue = 'ProCon enthält einen ungültigen Zahlenwert.'; }
}
return { key: local?.id ?? `remote-${remote!.Id}`, local, remote, differences, issue,
selectable: !!local && !!remote && !issue,
status: issue ? 'Nicht eindeutig / ungültig' : !local ? 'Nur ProCon' : !remote ? 'Nur MongoDB' : differences.length ? 'Unterschiede' : 'Gleich' };
};
return [
...data.table.rows.map(local => {
const matches = data.remote.filter(remote => remote.Nummer === local.parameterNr);
return compare(local, matches.length === 1 ? matches[0] : null,
matches.length > 1 || data.table.rows.filter(row => row.parameterNr === local.parameterNr).length > 1);
}),
...data.remote.filter(remote => !localNumbers.has(remote.Nummer)).map(remote =>
compare(null, remote, data.remote.filter(row => row.Nummer === remote.Nummer).length > 1)),
].sort((left, right) => (left.local?.parameterNr ?? left.remote!.Nummer) - (right.local?.parameterNr ?? right.remote!.Nummer));
}
async compareAll() {
const data = await this.loadAll();
return { anlageId: data.anlageId, verbindungId: data.verbindungId, version: data.version, rows: this.comparisonRows(data) };
}
async applyAll(dto: ParameterBulkSyncRequest) {
if (!dto || !['toLocal', 'toProcon'].includes(dto.direction) || !Array.isArray(dto.ids) || !dto.ids.length
|| dto.ids.some(id => typeof id !== 'string') || new Set(dto.ids).size !== dto.ids.length) {
throw new BadRequestException('Eindeutige Parameter auswählen und Synchronisierungsrichtung angeben.');
}
const data = await this.loadAll();
if (dto.anlageId !== data.anlageId || dto.verbindungId !== data.verbindungId || dto.version !== data.version) {
throw new BadRequestException('Sammelvergleich geändert. Bitte neu laden.');
}
const comparisons = this.comparisonRows(data);
const selected = dto.ids.map(id => {
const pair = comparisons.find(pair => pair.local?.id === id);
if (!pair?.selectable) throw new BadRequestException('Ausgewählte Parameter fehlen oder sind nicht eindeutig zugeordnet.');
return { local: pair.local!, remote: pair.remote! };
});
const context = { anlageId: data.anlageId, verbindungId: data.verbindungId };
const checkCurrent = async () => {
if (JSON.stringify(await this.context()) !== JSON.stringify(context) || (await this.parameters.get()).version !== data.table.version) {
throw new BadRequestException('Anlage, Verbindung oder lokale Parameter inzwischen geändert.');
}
};
if (dto.direction === 'toLocal') {
const updates = new Map(selected.map(pair => [pair.local.id, { ...pair.local, ...remoteValues(pair.remote) }]));
await checkCurrent();
// Gesamte Auswahl mit einer einzigen versionsgeprüften MongoDB-Speicherung übernehmen.
return this.parameters.save({ ...data.table, rows: data.table.rows.map(row => updates.get(row.id) ?? row) });
}
for (const { local } of selected) {
if (local.skalierungSps !== null && (!Number.isSafeInteger(local.skalierungSps) || local.skalierungSps < -2147483648 || local.skalierungSps > 2147483647)) {
throw new BadRequestException(`Parameter ${local.parameterNr}: ProCon erwartet eine ganzzahlige SPS-Skalierung im Int-Bereich.`);
}
}
const transaction = new sql.Transaction(data.pool);
await transaction.begin(sql.ISOLATION_LEVEL.SERIALIZABLE);
try {
const current = (await new sql.Request(transaction).query(
`SELECT ${snapshotColumns} FROM ParameterTyp WITH (UPDLOCK,HOLDLOCK) WHERE Kategorie=13 ORDER BY Nummer,Id`)).recordset;
if (JSON.stringify(current) !== JSON.stringify(data.remote)) throw new BadRequestException('ProCon-Parameter inzwischen geändert. Vergleich neu laden.');
for (const { local, remote } of selected) {
await updateComparedRow(transaction, 'ParameterTyp', remote.Id, {
Nummer: local.parameterNr, Kategorie: 13, Text: local.beschreibung,
Minimum: local.min === null ? null : String(local.min), Maximum: local.max === null ? null : String(local.max),
DefaultWert: local.startwert === null ? null : String(local.startwert), Einheit: local.wertigkeit, Skalierung: local.skalierungSps,
}, remote);
await this.writeValue(transaction, local, remote);
}
await checkCurrent();
await transaction.commit();
} catch (cause) { await transaction.rollback().catch(() => undefined); throw cause; }
return this.parameters.get();
}
private async writeValue(transaction: sql.Transaction, local: ParameterRow, remote: RemoteParameter) {
if (remote.WertAnzahl !== 1 || !remote.ParameterId) throw new BadRequestException('ProCon-Parameterwert fehlt oder ist mehrfach vorhanden.');
const values = (await new sql.Request(transaction).input('definitionId', sql.Int, remote.Id).query(
'SELECT Id,Wert FROM Parameter WITH (UPDLOCK,HOLDLOCK) WHERE ParameterTypId=@definitionId')).recordset;
if (values.length !== 1 || values[0].Id !== remote.ParameterId || values[0].Wert !== remote.Wert) {
throw new BadRequestException('ProCon-Wert inzwischen geaendert. Vergleich neu laden.');
}
let wert = local.wert ?? null;
validateParameterValue(wert, remote.TypeString ?? '');
if (wert !== null && ['System.Double', 'System.Int32'].includes(remote.TypeString ?? '')) {
wert = wert.trim().replace(',', '.');
const number = Number(wert);
if (local.min !== null && number < local.min || local.max !== null && number > local.max) {
throw new BadRequestException('Parameterwert ausserhalb Min/Max.');
}
}
await updateComparedRow(transaction, 'Parameter', remote.ParameterId,
{ Wert: wert, ParameterTypId: remote.Id }, { Wert: remote.Wert, ParameterTypId: remote.Id });
}
async apply(id: string, dto: ParameterSyncRequest) { async apply(id: string, dto: ParameterSyncRequest) {
if (!dto || !['toLocal', 'toProcon'].includes(dto.direction)) throw new BadRequestException('Synchronisierungsrichtung auswählen'); if (!dto || !['toLocal', 'toProcon'].includes(dto.direction)) throw new BadRequestException('Synchronisierungsrichtung auswählen');
const data = await this.load(id); const data = await this.load(id);
@@ -66,7 +256,7 @@ export class ParameterSyncService {
const context = { anlageId: data.anlageId, verbindungId: data.verbindungId }; const context = { anlageId: data.anlageId, verbindungId: data.verbindungId };
if (dto.direction === 'toLocal') { if (dto.direction === 'toLocal') {
const remote = data.remote; const remote = data.remote;
const row = { ...data.row, beschreibung: remote.Text ?? '', min: parseProconNumber(remote.Minimum), max: parseProconNumber(remote.Maximum), const row = { ...data.row, wert: remote.Wert ?? null, beschreibung: remote.Text ?? '', min: parseProconNumber(remote.Minimum), max: parseProconNumber(remote.Maximum),
startwert: parseProconNumber(remote.DefaultWert), wertigkeit: remote.Einheit ?? '', skalierungSps: parseProconNumber(remote.Skalierung) }; startwert: parseProconNumber(remote.DefaultWert), wertigkeit: remote.Einheit ?? '', skalierungSps: parseProconNumber(remote.Skalierung) };
if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung geändert'); if (JSON.stringify(await this.context()) !== JSON.stringify(context)) throw new BadRequestException('Anlage oder Verbindung geändert');
return this.parameters.save({ ...data.table, rows: data.table.rows.map(item => item.id === id ? row : item) }); return this.parameters.save({ ...data.table, rows: data.table.rows.map(item => item.id === id ? row : item) });
@@ -83,6 +273,7 @@ export class ParameterSyncService {
Nummer: row.parameterNr, Kategorie: 13, Text: row.beschreibung, Minimum: row.min === null ? null : String(row.min), Nummer: row.parameterNr, Kategorie: 13, Text: row.beschreibung, Minimum: row.min === null ? null : String(row.min),
Maximum: row.max === null ? null : String(row.max), DefaultWert: row.startwert === null ? null : String(row.startwert), Einheit: row.wertigkeit, Skalierung: row.skalierungSps, Maximum: row.max === null ? null : String(row.max), DefaultWert: row.startwert === null ? null : String(row.startwert), Einheit: row.wertigkeit, Skalierung: row.skalierungSps,
}, data.remote); }, data.remote);
await this.writeValue(transaction, row, data.remote);
if (JSON.stringify(await this.context()) !== JSON.stringify(context) || (await this.parameters.get()).version !== data.table.version) if (JSON.stringify(await this.context()) !== JSON.stringify(context) || (await this.parameters.get()).version !== data.table.version)
throw new BadRequestException('Anlage, Verbindung oder lokale Daten inzwischen geändert'); throw new BadRequestException('Anlage, Verbindung oder lokale Daten inzwischen geändert');
await transaction.commit(); await transaction.commit();
+38 -4
View File
@@ -11,23 +11,57 @@ describe('Parameter synchronization', () => {
const request: ParameterSyncRequest = { anlageId: 'a', verbindungId: 'v', version: 'hash', direction: 'toProcon' }; const request: ParameterSyncRequest = { anlageId: 'a', verbindungId: 'v', version: 'hash', direction: 'toProcon' };
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
const row = { id: 'p', parameterNr: 0, beschreibung: 'Warnung', min: 5, max: 30, startwert: 8, wertigkeit: 'Sekunden', skalierungSps: 1000 }; const row = { id: 'p', parameterNr: 0, beschreibung: 'Warnung', min: 5, max: 30, wert: '12', startwert: 8, wertigkeit: 'Sekunden', skalierungSps: 1000 };
data = { anlageId: 'a', verbindungId: 'v', version: 'hash', pool: {}, row, table: { anlageId: 'a', version: 2, reservedCount: 40, rows: [row] }, data = { anlageId: 'a', verbindungId: 'v', version: 'hash', pool: {}, row, table: { anlageId: 'a', version: 2, reservedCount: 40, rows: [row] },
remote: { Id: 47, Nummer: 0, Kategorie: 13, Text: 'Remote', Minimum: '1,5', Maximum: '40', DefaultWert: '7', Einheit: 's', Skalierung: 1 } }; remote: { Wert: '0', ParameterId: 70, WertAnzahl: 1, TypeString: 'System.Int32', Id: 47, Nummer: 0, Kategorie: 13, Text: 'Remote', Minimum: '1,5', Maximum: '40', DefaultWert: '7', Einheit: 's', Skalierung: 1 } };
parameters = { get: jest.fn(async () => data.table), save: jest.fn(async (table: any) => table) }; parameters = { get: jest.fn(async () => data.table), save: jest.fn(async (table: any) => table) };
service = new ParameterSyncService(parameters, {} as any, {} as any); service = new ParameterSyncService(parameters, {} as any, {} as any);
jest.spyOn(service as any, 'load').mockImplementation(async () => data); jest.spyOn(service as any, 'load').mockImplementation(async () => data);
jest.spyOn(service as any, 'context').mockResolvedValue({ anlageId: 'a', verbindungId: 'v' }); jest.spyOn(service as any, 'context').mockResolvedValue({ anlageId: 'a', verbindungId: 'v' });
transaction = { begin: jest.fn(async () => undefined), commit: jest.fn(async () => undefined), rollback: jest.fn(async () => undefined) }; transaction = { begin: jest.fn(async () => undefined), commit: jest.fn(async () => undefined), rollback: jest.fn(async () => undefined) };
(sql.Transaction as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => transaction); (sql.Transaction as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => transaction);
query = { input: jest.fn(() => query), query: jest.fn<() => Promise<any>>().mockResolvedValue({ recordset: [{ Id: 47 }] }) }; query = { input: jest.fn(() => query), query: jest.fn<(...args: any[]) => Promise<any>>().mockImplementation(async (...args: any[]) => ({ recordset: String(args[0]).includes('SELECT Id,Wert') ? [{ Id: 70, Wert: '0' }] : [{ Id: 47 }] })) };
(sql.Request as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => query); (sql.Request as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => query);
}); });
it('reads stored ProCon values separately and preserves zero, empty and multiple instances', async () => {
const values = [
{ parameterNr: 0, definitionId: 47, parameterId: 70, wert: '0' },
{ parameterNr: 0, definitionId: 47, parameterId: 71, wert: '' },
{ parameterNr: 1, definitionId: 48, parameterId: null, wert: null },
];
const read = jest.fn(async () => ({ recordset: values }));
(service as any).db.getPool = jest.fn(async () => ({ request: () => ({ query: read }) }));
const result = await service.proconValues();
expect(result.values).toEqual(values.map(value => ({ ...value, version: expect.any(String) })));
expect(read).toHaveBeenCalledWith(expect.stringContaining('LEFT JOIN Parameter p ON p.ParameterTypId=t.Id'));
expect(read).toHaveBeenCalledWith(expect.stringContaining('t.Kategorie=13'));
expect(parameters.save).not.toHaveBeenCalled();
expect(updateComparedRow).not.toHaveBeenCalled();
});
it('does not return ProCon values from a changed connection', async () => {
(service as any).db.getPool = jest.fn(async () => ({ request: () => ({ query: async () => ({ recordset: [] }) }) }));
(service as any).context.mockResolvedValueOnce({ anlageId: 'a', verbindungId: 'v' })
.mockResolvedValueOnce({ anlageId: 'a', verbindungId: 'changed' });
await expect(service.proconValues()).rejects.toThrow('Verbindung');
});
it('updates category 13 config only and preserves numeric-string storage', async () => { it('updates category 13 config only and preserves numeric-string storage', async () => {
await service.apply('p', request); await service.apply('p', request);
expect(updateComparedRow).toHaveBeenCalledWith(transaction, 'ParameterTyp', 47, { Nummer: 0, Kategorie: 13, Text: 'Warnung', Minimum: '5', Maximum: '30', DefaultWert: '8', Einheit: 'Sekunden', Skalierung: 1000 }, data.remote); expect(updateComparedRow).toHaveBeenCalledWith(transaction, 'ParameterTyp', 47, { Nummer: 0, Kategorie: 13, Text: 'Warnung', Minimum: '5', Maximum: '30', DefaultWert: '8', Einheit: 'Sekunden', Skalierung: 1000 }, data.remote);
expect(query.query.mock.calls[0][0]).toContain('Kategorie=13 AND Nummer=@nr'); expect(transaction.commit).toHaveBeenCalled(); expect(query.query.mock.calls[0][0]).toContain('Kategorie=13 AND Nummer=@nr'); expect(transaction.commit).toHaveBeenCalled();
}); });
it('writes local value to Parameter independently of the default value', async () => {
data.row.wert = '0'; data.row.min = 0;
await service.apply('p', request);
expect(updateComparedRow).toHaveBeenCalledWith(transaction, 'Parameter', 70,
{ Wert: '0', ParameterTypId: 47 }, { Wert: '0', ParameterTypId: 47 });
});
it('rolls back a value changed after comparison', async () => {
query.query.mockResolvedValueOnce({ recordset: [{ Id: 47 }] })
.mockResolvedValueOnce({ recordset: [{ Id: 70, Wert: '9' }] });
await expect(service.apply('p', request)).rejects.toThrow('Vergleich neu laden');
expect(transaction.rollback).toHaveBeenCalled();
expect(transaction.commit).not.toHaveBeenCalled();
});
it('deletes only ProCon category 13 in a transaction and preserves local parameters', async () => { it('deletes only ProCon category 13 in a transaction and preserves local parameters', async () => {
(service as any).db.getPool = jest.fn(async () => ({})); (service as any).db.getPool = jest.fn(async () => ({}));
query.query.mockResolvedValueOnce({ rowsAffected: [7] }); query.query.mockResolvedValueOnce({ rowsAffected: [7] });
@@ -56,7 +90,7 @@ describe('Parameter synchronization', () => {
}); });
it('imports values with decimal commas without changing number or identity', async () => { it('imports values with decimal commas without changing number or identity', async () => {
await service.apply('p', { ...request, direction: 'toLocal' }); await service.apply('p', { ...request, direction: 'toLocal' });
expect(parameters.save.mock.calls[0][0].rows[0]).toMatchObject({ id: 'p', parameterNr: 0, beschreibung: 'Remote', min: 1.5, max: 40, startwert: 7, wertigkeit: 's', skalierungSps: 1 }); expect(parameters.save.mock.calls[0][0].rows[0]).toMatchObject({ id: 'p', parameterNr: 0, beschreibung: 'Remote', wert: '0', min: 1.5, max: 40, startwert: 7, wertigkeit: 's', skalierungSps: 1 });
expect(data.row.beschreibung).toBe('Warnung'); expect(transaction.begin).not.toHaveBeenCalled(); expect(data.row.beschreibung).toBe('Warnung'); expect(transaction.begin).not.toHaveBeenCalled();
}); });
it('rejects stale contexts and non-integer SPS scaling before writing', async () => { it('rejects stale contexts and non-integer SPS scaling before writing', async () => {
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
jest.mock('./parameter.service', () => ({ ParameterService: class {} }));
jest.mock('../../infrastructure/sql/sql.service', () => ({ SqlService: class {} }));
jest.mock('../../visualisierung/shared/procon-sync', () => ({ updateComparedRow: jest.fn<() => Promise<void>>() }));
jest.mock('mssql', () => ({ ...jest.requireActual('mssql') as object, Transaction: jest.fn(), Request: jest.fn() }));
import * as sql from 'mssql';
import { ParameterSyncService } from './parameter-sync.service';
import { updateComparedRow } from '../../visualisierung/shared/procon-sync';
describe('Aktuellen ProCon-Parameterwert bearbeiten', () => {
let service: ParameterSyncService, row: any, transaction: any, query: any;
const context = { anlageId: 'a', verbindungId: 'v' };
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(updateComparedRow).mockReset().mockResolvedValue(undefined);
row = { parameterNr: 0, definitionId: 47, parameterId: 70, wert: '5', dataType: 'System.Double', minimum: '0', maximum: '100' };
service = new ParameterSyncService({} as any, { getPool: async () => ({}) } as any, {} as any);
jest.spyOn(service as any, 'context').mockResolvedValue(context);
transaction = { begin: jest.fn(async () => undefined), commit: jest.fn(async () => undefined), rollback: jest.fn(async () => undefined) };
(sql.Transaction as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => transaction);
query = { input: jest.fn(), query: jest.fn(async () => ({ recordset: [row] })) };
query.input.mockReturnValue(query);
(sql.Request as unknown as ReturnType<typeof jest.fn>).mockImplementation(() => query);
});
function dto(wert: string | null) {
return { ...context, parameterId: 70, version: (service as any).valueVersion(context, row), wert };
}
it('schreibt nur Wert und Definition der konkreten Instanz, normalisiert Dezimalkomma und commitet', async () => {
await expect(service.setProconValue(dto('12,5'))).resolves.toEqual({ parameterId: 70, wert: '12.5' });
expect(query.input).toHaveBeenCalledWith('id', sql.Int, 70);
expect(query.query).toHaveBeenCalledWith(expect.stringContaining('t.Kategorie=13 AND p.Id=@id'));
expect(updateComparedRow).toHaveBeenCalledWith(transaction, 'Parameter', 70,
{ Wert: '12.5', ParameterTypId: 47 }, { Wert: '5', ParameterTypId: 47 });
expect(transaction.commit).toHaveBeenCalled();
});
it('übernimmt Null und echte Nullwerte ohne Rückgriff auf den Startwert', async () => {
await service.setProconValue(dto('0'));
expect(updateComparedRow).toHaveBeenLastCalledWith(transaction, 'Parameter', 70,
{ Wert: '0', ParameterTypId: 47 }, { Wert: '5', ParameterTypId: 47 });
await service.setProconValue(dto(null));
expect(updateComparedRow).toHaveBeenLastCalledWith(transaction, 'Parameter', 70,
{ Wert: null, ParameterTypId: 47 }, { Wert: '5', ParameterTypId: 47 });
});
it('verhindert Überschreiben geänderter Werte oder Definitionen', async () => {
const request = dto('10');
row.wert = '8';
await expect(service.setProconValue(request)).rejects.toThrow('inzwischen geändert');
expect(updateComparedRow).not.toHaveBeenCalled();
expect(transaction.rollback).toHaveBeenCalled();
});
it('weist Bereichsverletzungen und ungültige Datentypwerte vor dem Schreiben ab', async () => {
await expect(service.setProconValue(dto('101'))).rejects.toThrow('innerhalb');
row.dataType = 'System.Int32';
await expect(service.setProconValue(dto('1.5'))).rejects.toThrow('Int32');
row.dataType = 'System.Boolean';
await expect(service.setProconValue(dto('1'))).rejects.toThrow('true oder false');
expect(updateComparedRow).not.toHaveBeenCalled();
});
it('rollt Fehler und einen Verbindungswechsel zurück', async () => {
jest.mocked(updateComparedRow).mockRejectedValueOnce(new Error('Schreibkonflikt'));
await expect(service.setProconValue(dto('10'))).rejects.toThrow('Schreibkonflikt');
(service as any).context.mockResolvedValueOnce(context).mockResolvedValueOnce({ ...context, verbindungId: 'andere' });
await expect(service.setProconValue(dto('10'))).rejects.toThrow('Verbindung');
expect(transaction.rollback).toHaveBeenCalledTimes(2);
expect(transaction.commit).not.toHaveBeenCalled();
});
});
@@ -2,10 +2,14 @@ import { Body, Controller, Get, Put, Post, Param, StreamableFile } from '@nestjs
import { ParameterService } from './parameter.service'; import { ParameterService } from './parameter.service';
import type { ParameterTable } from './parameter.dto'; import type { ParameterTable } from './parameter.dto';
import { createParameterExcel } from './parameter.excel'; import { createParameterExcel } from './parameter.excel';
import { ParameterSyncService, type ParameterSyncRequest } from './parameter-sync.service'; import { ParameterSyncService, type ParameterSyncRequest, type ParameterBulkSyncRequest, type ProconParameterValueRequest } from './parameter-sync.service';
@Controller('rk2/parameter') @Controller('rk2/parameter')
export class ParameterController { export class ParameterController {
constructor(private readonly parameters: ParameterService, private readonly sync: ParameterSyncService) {} constructor(private readonly parameters: ParameterService, private readonly sync: ParameterSyncService) {}
@Get('procon-values') proconValues() { return this.sync.proconValues(); }
@Post('procon-values') setProconValue(@Body() dto: ProconParameterValueRequest) { return this.sync.setProconValue(dto); }
@Get('sync-all') compareAll() { return this.sync.compareAll(); }
@Post('sync-all') applyAll(@Body() dto: ParameterBulkSyncRequest) { return this.sync.applyAll(dto); }
@Post('delete-procon') deleteProcon(@Body() dto: { anlageId: string; version: number }) { return this.sync.deleteAll(dto); } @Post('delete-procon') deleteProcon(@Body() dto: { anlageId: string; version: number }) { return this.sync.deleteAll(dto); }
@Get(':id/sync') compare(@Param('id') id: string) { return this.sync.compare(id); } @Get(':id/sync') compare(@Param('id') id: string) { return this.sync.compare(id); }
@Post(':id/sync') apply(@Param('id') id: string, @Body() dto: ParameterSyncRequest) { return this.sync.apply(id, dto); } @Post(':id/sync') apply(@Param('id') id: string, @Body() dto: ParameterSyncRequest) { return this.sync.apply(id, dto); }
+2 -1
View File
@@ -1,13 +1,14 @@
import { BadRequestException } from '@nestjs/common'; import { BadRequestException } from '@nestjs/common';
export interface ParameterRow { export interface ParameterRow {
id: string; parameterNr: number; beschreibung: string; min: number | null; max: number | null; id: string; parameterNr: number; beschreibung: string; min: number | null; max: number | null;
startwert: number | null; wertigkeit: string; skalierungSps: number | null; wert?: string | null; startwert: number | null; wertigkeit: string; skalierungSps: number | null;
} }
export interface ParameterTable { anlageId: string; version: number; reservedCount: number; rows: ParameterRow[] } export interface ParameterTable { anlageId: string; version: number; reservedCount: number; rows: ParameterRow[] }
export function validateParameters(table: ParameterTable) { export function validateParameters(table: ParameterTable) {
if (!table || typeof table.anlageId !== 'string' || !table.anlageId || !Number.isSafeInteger(table.version) || table.version < 0 || if (!table || typeof table.anlageId !== 'string' || !table.anlageId || !Number.isSafeInteger(table.version) || table.version < 0 ||
!Number.isSafeInteger(table.reservedCount) || table.reservedCount < 1 || table.reservedCount > 10000 || !Array.isArray(table.rows) || table.rows.length > table.reservedCount) !Number.isSafeInteger(table.reservedCount) || table.reservedCount < 1 || table.reservedCount > 10000 || !Array.isArray(table.rows) || table.rows.length > table.reservedCount)
throw new BadRequestException('Ungültige Parameter-Tabelle'); throw new BadRequestException('Ungültige Parameter-Tabelle');
if (table.rows.some(row => row?.wert != null && (typeof row.wert !== 'string' || row.wert.length > 10000))) throw new BadRequestException('Ung?ltiger Parameterwert');
const ids = new Set<string>(), numbers = new Set<number>(); const ids = new Set<string>(), numbers = new Set<number>();
for (const row of table.rows) { for (const row of table.rows) {
if (!row || typeof row.id !== 'string' || !/^[\w-]{1,80}$/.test(row.id) || ids.has(row.id) || !Number.isSafeInteger(row.parameterNr) || row.parameterNr < 0 || row.parameterNr >= table.reservedCount || numbers.has(row.parameterNr) || if (!row || typeof row.id !== 'string' || !/^[\w-]{1,80}$/.test(row.id) || ids.has(row.id) || !Number.isSafeInteger(row.parameterNr) || row.parameterNr < 0 || row.parameterNr >= table.reservedCount || numbers.has(row.parameterNr) ||
+2 -2
View File
@@ -16,8 +16,8 @@ export class ParameterService {
async save(input: ParameterTable) { async save(input: ParameterTable) {
validateParameters(input); validateParameters(input);
if ((await this.anlagen.getSelected()).id !== input.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.'); if ((await this.anlagen.getSelected()).id !== input.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.');
const rows = input.rows.map(({ id, parameterNr, beschreibung, min, max, startwert, wertigkeit, skalierungSps }) => const rows = input.rows.map(({ id, parameterNr, beschreibung, min, max, startwert, wert, wertigkeit, skalierungSps }) =>
({ id, parameterNr, beschreibung, min, max, startwert, wertigkeit, skalierungSps })); ({ id, parameterNr, beschreibung, min, max, startwert, wert, wertigkeit, skalierungSps }));
try { try {
const result = await this.model.updateOne({ anlageId: input.anlageId, revision: input.version }, { const result = await this.model.updateOne({ anlageId: input.anlageId, revision: input.version }, {
$set: { rows, reservedCount: input.reservedCount }, $inc: { revision: 1 }, $set: { rows, reservedCount: input.reservedCount }, $inc: { revision: 1 },
+11
View File
@@ -49,6 +49,17 @@ describe('Anlagenparameter', () => {
} }
expect(() => validateParameters(fixture())).not.toThrow(); expect(() => validateParameters(fixture())).not.toThrow();
}); });
it('persists the local value independently of startwert and reads it back', async () => {
const table = fixture();
table.rows[0].wert = '0';
const { service, updateOne } = setup();
const saved = await service.save(table);
expect(updateOne.mock.calls[0][1].$set.rows[0]).toMatchObject({ wert: '0', startwert: 8 });
const reader = setup({ revision: saved.version, reservedCount: 40, rows: saved.rows });
expect((await reader.service.get()).rows[0].wert).toBe('0');
table.rows[0].wert = null;
expect((await service.save(table)).rows[0].wert).toBeNull();
});
it('blocks saves to a different plant or an outdated revision', async () => { it('blocks saves to a different plant or an outdated revision', async () => {
const { service, updateOne } = setup(); const { service, updateOne } = setup();
await expect(service.save({ ...fixture(), anlageId: 'other' })).rejects.toThrow('Anlage'); expect(updateOne).not.toHaveBeenCalled(); await expect(service.save({ ...fixture(), anlageId: 'other' })).rejects.toThrow('Anlage'); expect(updateOne).not.toHaveBeenCalled();
@@ -0,0 +1,61 @@
import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import { mkdtemp, rmdir, unlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { AnlagePdfController } from './anlage-pdf.controller';
import { AnlagePdfService } from './anlage-pdf.service';
describe('AnlagePdfController HTTP', () => {
let app: INestApplication;
let base: string;
let directory: string;
let file: string;
const service = {
metadata: jest.fn(async () => null), unitReferences: jest.fn(async () => []),
file: jest.fn(), upload: jest.fn(async () => ({ version: 'new' })),
setPage: jest.fn(async () => ({ unitPages: { unit: 7 } })),
};
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), 'rk-pdf-http-'));
file = join(directory, 'plan.pdf');
await writeFile(file, '%PDF-1.7\nfixture');
service.file.mockResolvedValue(file);
const module = await Test.createTestingModule({ controllers: [AnlagePdfController],
providers: [{ provide: AnlagePdfService, useValue: service }] }).compile();
app = module.createNestApplication();
await app.listen(0, '127.0.0.1');
base = `${await app.getUrl()}/anlage/plant/pdf`;
});
afterAll(async () => { await app?.close(); await unlink(file); await rmdir(directory); });
it('serves absent metadata and plant units through the expected routes', async () => {
const response = await fetch(base);
// Nest beendet eine null-Antwort ohne JSON-Body; das Frontend benötigt explizites JSON null.
expect(response.status).toBe(200);
expect(await response.text()).toBe('null');
const units = await fetch(`${base}/units`);
expect(await units.json()).toEqual([]);
expect(service.unitReferences).toHaveBeenCalledWith('plant');
});
it('serves PDF byte ranges and forwards the expected version', async () => {
const response = await fetch(`${base}/file?version=test-version`, { headers: { Range: 'bytes=0-4' } });
expect(response.status).toBe(206);
expect(await response.text()).toBe('%PDF-');
expect(response.headers.get('content-type')).toContain('application/pdf');
expect(service.file).toHaveBeenCalledWith('plant', 'test-version');
});
it('parses PDF multipart uploads and page assignments', async () => {
const form = new FormData();
form.set('file', new Blob(['%PDF-1.7'], { type: 'application/pdf' }), 'plan.pdf');
const upload = await fetch(base, { method: 'POST', body: form });
expect(upload.status).toBe(201);
expect(service.upload).toHaveBeenCalledWith('plant', expect.objectContaining({ originalname: 'plan.pdf', size: 8 }));
const patch = await fetch(`${base}/units/unit`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ version: 'new', page: 7 }) });
expect(patch.status).toBe(200);
expect(service.setPage).toHaveBeenCalledWith('plant', 'unit', { version: 'new', page: 7 });
});
});
+36
View File
@@ -0,0 +1,36 @@
import { Body, Controller, Get, Param, Patch, Post, Query, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { AnlagePdfService } from './anlage-pdf.service';
@Controller('anlage/:anlageId/pdf')
export class AnlagePdfController {
constructor(private readonly service: AnlagePdfService) {}
@Get()
async metadata(@Param('anlageId') id: string, @Res() response: Response) {
response.json(await this.service.metadata(id));
}
@Get('units')
units(@Param('anlageId') id: string) { return this.service.unitReferences(id); }
@Get('file')
async file(@Param('anlageId') id: string, @Query('version') version: string | undefined, @Res() response: Response) {
const path = await this.service.file(id, version);
response.setHeader('Cache-Control', 'private, no-store');
response.type('application/pdf').sendFile(path);
}
@Post()
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 100 * 1024 * 1024, files: 1 } }))
upload(@Param('anlageId') id: string, @UploadedFile() file?: Express.Multer.File) {
return this.service.upload(id, file);
}
@Patch('units/:unitId')
setPage(@Param('anlageId') id: string, @Param('unitId') unitId: string,
@Body() dto: { version: string; page: number | null }) {
return this.service.setPage(id, unitId, dto);
}
}
+18
View File
@@ -0,0 +1,18 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AnlageModule } from '../../rk-anlagen/anlage/anlage.module';
import { Unit, UnitSchema } from '../../_schemas/anlagen/units';
import { Signal, SignalSchema } from '../../_schemas/anlagen/singnals';
import { IO, IOSchema } from '../../_schemas/anlagen/ios';
import { AnlagePdf, AnlagePdfSchema } from './anlage-pdf.schema';
import { AnlagePdfController } from './anlage-pdf.controller';
import { AnlagePdfService } from './anlage-pdf.service';
@Module({
imports: [AnlageModule, MongooseModule.forFeature([
{ name: AnlagePdf.name, schema: AnlagePdfSchema }, { name: Unit.name, schema: UnitSchema },
{ name: Signal.name, schema: SignalSchema }, { name: IO.name, schema: IOSchema },
], 'anlagen')],
controllers: [AnlagePdfController], providers: [AnlagePdfService],
})
export class AnlagePdfModule {}
+22
View File
@@ -0,0 +1,22 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Types } from 'mongoose';
@Schema({ collection: 'anlage_pdfs', timestamps: true })
export class AnlagePdf {
@Prop({ type: Types.ObjectId, required: true, unique: true })
anlageId!: Types.ObjectId;
@Prop({ required: true })
version!: string;
@Prop({ required: true })
filename!: string;
@Prop({ required: true })
size!: number;
@Prop({ type: Object, default: {} })
unitPages!: Record<string, number>;
}
export const AnlagePdfSchema = SchemaFactory.createForClass(AnlagePdf);
@@ -0,0 +1,81 @@
import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';
import { Types } from 'mongoose';
import { mkdir, unlink, writeFile } from 'node:fs/promises';
import { AnlagePdfService } from './anlage-pdf.service';
jest.mock('node:fs/promises', () => ({ mkdir: jest.fn(), unlink: jest.fn(), writeFile: jest.fn() }));
describe('AnlagePdfService', () => {
const anlageId = new Types.ObjectId();
const unitId = new Types.ObjectId();
const componentId = new Types.ObjectId();
const ioId = new Types.ObjectId();
const version = 'b36ecb94-9dc7-4b68-9d69-c5865488ff53';
const query = (value: unknown) => ({ lean: () => ({ exec: async () => value }), exec: async () => value });
let service: AnlagePdfService;
let pdfs: any;
let units: any;
let signals: any;
let ios: any;
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(mkdir).mockResolvedValue(undefined);
jest.mocked(writeFile).mockResolvedValue(undefined);
jest.mocked(unlink).mockResolvedValue(undefined);
pdfs = {
findOne: jest.fn(() => query({ version, filename: 'Plan.pdf', unitPages: {} })),
findOneAndUpdate: jest.fn(() => query({ version })),
updateOne: jest.fn(() => query({ matchedCount: 1 })),
};
units = { exists: jest.fn(async () => ({ _id: unitId })), find: jest.fn(() => query([
{ _id: unitId, name: 'SC', prefix: 'BA1', components: [{ _id: componentId }] },
])) };
signals = { find: jest.fn(() => query([{ componentId, ioId, description: '102 · =BAI-ET+29/5' }])) };
ios = { find: jest.fn(() => query([{ _id: ioId, seiteName: '=BAI-ET+29/5', functionText: 'SC' }])) };
service = new AnlagePdfService(pdfs, units, signals, ios, { findOne: async () => ({}) } as any);
});
it('collects unique EPLAN references through the unit component/signal/IO chain within the plant', async () => {
expect(await service.unitReferences(anlageId.toString())).toEqual([
{ id: unitId.toString(), name: 'SC', label: 'BA1_SC', references: ['=BAI-ET+29/5'] },
]);
expect(units.find).toHaveBeenCalledWith({ anlageId });
expect(signals.find).toHaveBeenCalledWith({ anlageId, componentId: { $in: [componentId] } });
expect(ios.find).toHaveBeenCalledWith({ anlageId, _id: { $in: [ioId] } });
});
it('rejects invalid files before writing and scopes paths by validated plant ID', async () => {
await expect(service.upload(anlageId.toString(), { buffer: Buffer.from('not a pdf') } as any)).rejects.toThrow(BadRequestException);
await expect(service.file('../escape')).rejects.toThrow(BadRequestException);
expect(writeFile).not.toHaveBeenCalled();
});
it('replaces metadata and resets page assignments only after writing the new PDF', async () => {
await service.upload(anlageId.toString(), { buffer: Buffer.from('%PDF-1.7'), originalname: 'plan.pdf', size: 8 } as any);
expect(pdfs.findOneAndUpdate).toHaveBeenCalledWith({ anlageId }, { $set: {
version: expect.any(String), filename: 'plan.pdf', size: 8, unitPages: {},
} }, expect.objectContaining({ upsert: true }));
expect(unlink).toHaveBeenCalledWith(expect.stringContaining(version));
expect(jest.mocked(writeFile).mock.invocationCallOrder[0]).toBeLessThan(pdfs.findOneAndUpdate.mock.invocationCallOrder[0]);
});
it('removes a new file if saving metadata fails', async () => {
pdfs.findOneAndUpdate.mockReturnValue({ lean: () => ({ exec: async () => { throw new Error('database failed'); } }) });
await expect(service.upload(anlageId.toString(), { buffer: Buffer.from('%PDF-1.7'), originalname: 'plan.pdf', size: 8 } as any)).rejects.toThrow('database failed');
expect(unlink).toHaveBeenCalledWith(jest.mocked(writeFile).mock.calls[0][0]);
});
it('does not assign pages to units outside this plant', async () => {
units.exists.mockResolvedValue(null);
await expect(service.setPage(anlageId.toString(), unitId.toString(), { version, page: 5 })).rejects.toThrow(NotFoundException);
expect(pdfs.updateOne).not.toHaveBeenCalled();
});
it('prevents stale assignments after the PDF was replaced and rejects invalid page numbers', async () => {
pdfs.updateOne.mockReturnValue(query({ matchedCount: 0 }));
await expect(service.setPage(anlageId.toString(), unitId.toString(), { version, page: 5 })).rejects.toThrow(ConflictException);
await expect(service.setPage(anlageId.toString(), unitId.toString(), { version, page: 0 })).rejects.toThrow(BadRequestException);
expect(pdfs.updateOne).toHaveBeenCalledWith({ anlageId, version }, { $set: { [`unitPages.${unitId}`]: 5 } });
});
});
+114
View File
@@ -0,0 +1,114 @@
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { randomUUID } from 'node:crypto';
import { mkdir, unlink, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { AnlagePdf } from './anlage-pdf.schema';
import { AnlageService } from '../../rk-anlagen/anlage/anlage.service';
import { Unit } from '../../_schemas/anlagen/units';
import { Signal } from '../../_schemas/anlagen/singnals';
import { IO } from '../../_schemas/anlagen/ios';
@Injectable()
export class AnlagePdfService {
private readonly root = resolve('data/anlagen-pdf');
constructor(
@InjectModel(AnlagePdf.name, 'anlagen') private readonly pdfs: Model<AnlagePdf>,
@InjectModel(Unit.name, 'anlagen') private readonly units: Model<Unit>,
@InjectModel(Signal.name, 'anlagen') private readonly signals: Model<Signal>,
@InjectModel(IO.name, 'anlagen') private readonly ios: Model<IO>,
private readonly anlagen: AnlageService,
) {}
private async anlage(id: string) {
if (!Types.ObjectId.isValid(id)) throw new BadRequestException('Ungültige Anlagen-ID');
if (!await this.anlagen.findOne(id)) throw new NotFoundException('Anlage nicht gefunden');
return new Types.ObjectId(id);
}
private filePath(id: string, version: string) {
if (!Types.ObjectId.isValid(id) || !/^[a-f0-9-]{36}$/.test(version)) {
throw new BadRequestException('Ungültige PDF-ID');
}
return join(this.root, id, `${version}.pdf`);
}
async metadata(id: string) {
const anlageId = await this.anlage(id);
const doc = await this.pdfs.findOne({ anlageId }).lean().exec();
return doc ? { filename: doc.filename, size: doc.size, version: doc.version, unitPages: doc.unitPages } : null;
}
async file(id: string, version?: string) {
const metadata = await this.metadata(id);
if (!metadata) throw new NotFoundException('Für diese Anlage ist keine PDF hinterlegt');
if (version && metadata.version !== version) throw new ConflictException('Die PDF wurde ersetzt. Bitte neu laden.');
return this.filePath(id, metadata.version);
}
async upload(id: string, file?: Express.Multer.File) {
const anlageId = await this.anlage(id);
if (!file || file.buffer.subarray(0, 5).toString('ascii') !== '%PDF-') {
throw new BadRequestException('Bitte eine gültige PDF-Datei hochladen');
}
const version = randomUUID();
const target = this.filePath(id, version);
await mkdir(join(this.root, id), { recursive: true });
await writeFile(target, file.buffer, { flag: 'wx' });
let previous: AnlagePdf | null;
try {
previous = await this.pdfs.findOneAndUpdate({ anlageId }, { $set: {
version, filename: file.originalname.replace(/[\\/\r\n]/g, '_'), size: file.size, unitPages: {},
} }, { upsert: true, returnDocument: 'before', runValidators: true }).lean().exec();
} catch (error) {
await unlink(target).catch(() => undefined);
throw error;
}
// Alte Versionen erst nach erfolgreichem Austausch entfernen.
if (previous) await unlink(this.filePath(id, previous.version)).catch(() => undefined);
return this.metadata(id);
}
async setPage(id: string, unitId: string, dto: { version: string; page: number | null }) {
const anlageId = await this.anlage(id);
if (!Types.ObjectId.isValid(unitId)) throw new BadRequestException('Ungültige Unit-ID');
if (!dto || typeof dto.version !== 'string' || (dto.page !== null && (!Number.isSafeInteger(dto.page) || dto.page < 1))) {
throw new BadRequestException('Eine positive PDF-Seitennummer ist erforderlich');
}
if (!await this.units.exists({ _id: new Types.ObjectId(unitId), anlageId })) {
throw new NotFoundException('Unit gehört nicht zu dieser Anlage');
}
const field = `unitPages.${unitId}`;
const result = await this.pdfs.updateOne({ anlageId, version: dto.version },
dto.page === null ? { $unset: { [field]: 1 } } : { $set: { [field]: dto.page } }).exec();
if (!result.matchedCount) throw new ConflictException('Die PDF wurde ersetzt oder fehlt. Bitte neu laden.');
return this.metadata(id);
}
async unitReferences(id: string) {
const anlageId = await this.anlage(id);
const units = await this.units.find({ anlageId }).lean().exec();
const componentIds = units.flatMap(unit => unit.components.map(c => c._id!).filter(Boolean));
const signals = await this.signals.find({ anlageId, componentId: { $in: componentIds } }).lean().exec();
const ioIds = signals.map(signal => signal.ioId).filter(Boolean);
const ios = await this.ios.find({ anlageId, _id: { $in: ioIds } }).lean().exec();
const byIo = new Map(ios.map(io => [io._id.toString(), io]));
const byComponent = new Map<string, string[]>();
for (const signal of signals) {
const io = signal.ioId ? byIo.get(signal.ioId.toString()) : undefined;
const texts = [signal.description, io?.seiteName, io?.functionText];
const references = texts.flatMap(text => text?.match(/=[^\s=·/,;]+\/\d+(?:\.\d+)?/g) ?? []);
if (signal.componentId) {
const key = signal.componentId.toString();
byComponent.set(key, [...(byComponent.get(key) ?? []), ...references]);
}
}
return units.map(unit => ({
id: unit._id.toString(), name: unit.name,
label: [unit.prefix, unit.bmk, unit.name, unit.postfix].filter(Boolean).join('_'),
references: [...new Set(unit.components.flatMap(c => byComponent.get(c._id?.toString() ?? '') ?? []))],
}));
}
}
@@ -45,3 +45,13 @@ export function validateAnalogTable(table: AnalogTable) {
} }
} }
} }
/** Wert und Grundbild teilen eine Position; Alarmgrafiken behalten ihre Zuordnung. */
export function normalizeAnalogPlacement(row: AnalogRow): AnalogRow {
const obsolete = new Set(row.graphics.filter(graphic => graphic.slot === 'grundbild').map(graphic => graphic.placementId));
obsolete.add('grafik');
const graphics = row.graphics.map(graphic => graphic.slot === 'grundbild'
? { ...graphic, placementId: row.valuePlacementId } : graphic);
const used = new Set([row.valuePlacementId, ...graphics.map(graphic => graphic.placementId)]);
return { ...row, graphics, placements: row.placements.filter(placement => used.has(placement.id) || !obsolete.has(placement.id)) };
}
@@ -7,7 +7,7 @@ import { AnlageService } from '../../rk-anlagen/anlage/anlage.service';
import { DrawService } from '../../draw/draw.service'; import { DrawService } from '../../draw/draw.service';
import { Unit } from '../../_schemas/anlagen/units'; import { Unit } from '../../_schemas/anlagen/units';
import { prepareBinding } from '../../visualisierung/shared/graphics'; import { prepareBinding } from '../../visualisierung/shared/graphics';
import { type AnalogTable, validateAnalogTable } from './sensoren-analog.dto'; import { type AnalogTable, validateAnalogTable, normalizeAnalogPlacement } from './sensoren-analog.dto';
import type { AnalogDocument } from './sensoren-analog.schema'; import type { AnalogDocument } from './sensoren-analog.schema';
import { analogFileName } from './sensoren-analog.excel'; import { analogFileName } from './sensoren-analog.excel';
@@ -19,7 +19,7 @@ export class AnalogService {
async get(): Promise<AnalogTable> { async get(): Promise<AnalogTable> {
const anlageId = (await this.anlagen.getSelected()).id; const anlageId = (await this.anlagen.getSelected()).id;
const doc = await this.model.findOne({ anlageId }).lean().exec(); const doc = await this.model.findOne({ anlageId }).lean().exec();
const table = { anlageId, version: doc?.revision ?? 0, reservedCount: doc?.reservedCount ?? 40, rows: doc?.rows ?? [] }; const table = { anlageId, version: doc?.revision ?? 0, reservedCount: doc?.reservedCount ?? 40, rows: (doc?.rows ?? []).map(normalizeAnalogPlacement) };
return this.library ? this.library.resolveTable(table) : table; return this.library ? this.library.resolveTable(table) : table;
} }
async sources() { async sources() {
@@ -30,6 +30,7 @@ export class AnalogService {
} }
async save(input: AnalogTable) { async save(input: AnalogTable) {
validateAnalogTable(input); validateAnalogTable(input);
input = { ...input, rows: input.rows.map(normalizeAnalogPlacement) };
if ((await this.anlagen.getSelected()).id !== input.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.'); if ((await this.anlagen.getSelected()).id !== input.anlageId) throw new BadRequestException('Anlage geändert. Neu laden.');
const linked = input.rows.filter(row => row.componentId); const linked = input.rows.filter(row => row.componentId);
if (linked.length) { if (linked.length) {
@@ -3,7 +3,7 @@ jest.mock('../../rk-anlagen/anlage/anlage.service', () => ({ AnlageService: clas
jest.mock('../../draw/draw.service', () => ({ DrawService: class {} })); jest.mock('../../draw/draw.service', () => ({ DrawService: class {} }));
jest.mock('../../_schemas/anlagen/units', () => ({ Unit: class Unit {} })); jest.mock('../../_schemas/anlagen/units', () => ({ Unit: class Unit {} }));
import * as XLSX from 'xlsx'; import * as XLSX from 'xlsx';
import { analogSlots, validateAnalogTable, type AnalogTable } from './sensoren-analog.dto'; import { analogSlots, validateAnalogTable, normalizeAnalogPlacement, type AnalogTable } from './sensoren-analog.dto';
import { AnalogService } from './sensoren-analog.service'; import { AnalogService } from './sensoren-analog.service';
import { createAnalogExcel } from './sensoren-analog.excel'; import { createAnalogExcel } from './sensoren-analog.excel';
import { AnalogController } from './sensoren-analog.controller'; import { AnalogController } from './sensoren-analog.controller';
@@ -37,6 +37,19 @@ describe('Sensoren Analog', () => {
table.rows[0].einheit = '%'; table.rows[0].prozentkasten = false; table.rows[0].einheit = '%'; table.rows[0].prozentkasten = false;
await service.save(table); expect(model.updateOne.mock.calls[1][1].$set.rows[0].prozentkasten).toBe(false); await service.save(table); expect(model.updateOne.mock.calls[1][1].$set.rows[0].prozentkasten).toBe(false);
}); });
it('uses one main position while retaining separate alarm positions', async () => {
const row = table.rows[0];
row.placements.push({ id: 'grafik', x: 0, y: 80, width: 60, height: 60, z: 0, show: true });
row.graphics.find(graphic => graphic.slot === 'grundbild')!.placementId = 'grafik';
const normalized = normalizeAnalogPlacement(row);
expect(normalized.graphics.find(graphic => graphic.slot === 'grundbild')!.placementId).toBe('wert');
expect(normalized.placements.map(p => p.id)).toEqual(['wert', 'bild']);
expect(normalized.graphics.filter(graphic => graphic.slot !== 'grundbild').every(graphic => graphic.placementId === 'bild')).toBe(true);
expect(row.placements).toHaveLength(3);
expect((await service.get()).rows[0]).toEqual(normalized);
await service.save(table);
expect(model.updateOne.mock.calls[0][1].$set.rows[0].placements.map((p: any) => p.id)).toEqual(['wert', 'bild']);
});
it('exportiert exakt zwölf Spalten mit Nummern 0–39 und identischen XAML-Dateinamen', async () => { it('exportiert exakt zwölf Spalten mit Nummern 0–39 und identischen XAML-Dateinamen', async () => {
const workbook = XLSX.read(createAnalogExcel(table), { type: 'buffer' }); const workbook = XLSX.read(createAnalogExcel(table), { type: 'buffer' });
const rows = XLSX.utils.sheet_to_json<(string | number)[]>(workbook.Sheets.Sensoren_Analog, { header: 1, defval: '' }); const rows = XLSX.utils.sheet_to_json<(string | number)[]>(workbook.Sheets.Sensoren_Analog, { header: 1, defval: '' });
@@ -0,0 +1,25 @@
import * as XLSX from 'xlsx';
import { ExcelRepo } from './signal.excel.repo';
describe('ExcelRepo E/A import', () => {
it('keeps addressed rows without text or card and ignores rows without an address', async () => {
const sheet = XLSX.utils.aoa_to_sheet([
['__EMPTY', '__EMPTY_1', '__EMPTY_2', '__EMPTY_3', '__EMPTY_4', '__EMPTY_5'],
['Titel'], ['Anlage'], ['Stand'], ['Spalten'],
['Karte 1', 'E0.0', null, 'Motor bereit', 1, '=BAI+26/1'],
['Karte 1', 'E0.1', null, null, 1, '=BAI+26/1'],
[null, ' E0.2 ', null, null, 1, '=BAI+26/1'],
['Karte 1', null, null, 'Keine E/A-Adresse'],
[null, 'E0.3', null, ' ', 1, '=BAI+26/1'],
]);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, sheet, 'EA');
const rows = await new ExcelRepo().getExcelData({
buffer: XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }),
} as Express.Multer.File);
expect(rows?.map(row => [row.spsAdr, row.functionText])).toEqual([
['E0.0', 'Motor bereit'], ['E0.1', ''], ['E0.2', ''], ['E0.3', ' '],
]);
expect(new ExcelRepo().plcAdr_String_To_Obj(rows![2].spsAdr)).toEqual({ adrType: 'I', adrByte: 0, adrBit: 2 });
});
});
+5 -3
View File
@@ -25,8 +25,11 @@ export class ExcelRepo {
if (index < 4) return; if (index < 4) return;
const spsKarte = d['__EMPTY']; const spsKarte = d['__EMPTY'];
const spsAdr = d['__EMPTY_1']; const rawAddress = d['__EMPTY_1'];
const functionTxt = d['__EMPTY_3']; // Adressierte Reserve-E/As auch ohne Funktionstext oder SPS-Karte übernehmen.
if (typeof rawAddress !== 'string' || !rawAddress.trim()) return;
const spsAdr = rawAddress.trim();
const functionTxt = d['__EMPTY_3'] ?? '';
const seite = typeof d['__EMPTY_4'] === 'number' ? Number.parseInt(d['__EMPTY_4'].toString()) : -1; const seite = typeof d['__EMPTY_4'] === 'number' ? Number.parseInt(d['__EMPTY_4'].toString()) : -1;
const seiteName = d['__EMPTY_5']; const seiteName = d['__EMPTY_5'];
@@ -37,7 +40,6 @@ export class ExcelRepo {
spsAdr: spsAdr, spsAdr: spsAdr,
spsKarte: spsKarte spsKarte: spsKarte
} }
if (spsKarte !== "" && spsKarte != undefined && spsKarte != null)
data.push(result) data.push(result)
}) })
+33
View File
@@ -0,0 +1,33 @@
import { model, Types } from 'mongoose';
import { UnitsService } from './units.service';
import { UnitSchema } from '../../_schemas/anlagen/units';
import { UnitTypeDto } from '../../_dto/anlagen/units';
describe('UnitsService.copy', () => {
it('copies legacy components with empty names using the existing fallback', async () => {
const anlageId = new Types.ObjectId();
const componentId = new Types.ObjectId();
const source = {
_id: new Types.ObjectId(), anlageId, name: 'SC', type: UnitTypeDto.GENERAL,
components: [{ _id: componentId, name: '', type: 'Allgemein' }],
};
const UnitModel = model('UnitCopyRegression', UnitSchema);
const save = jest.spyOn(UnitModel.prototype, 'save').mockImplementation(async function () { return this; });
const find = jest.spyOn(UnitModel, 'findById').mockReturnValue({ exec: async () => source } as any);
const signals = { find: jest.fn(() => ({ exec: async () => [] })) };
const service = new UnitsService(UnitModel as any, signals as any, {} as any,
{ getSelected: async () => ({ id: anlageId.toString() }) } as any);
try {
const result = await service.copy(source._id.toString(), { name: 'SC Kopie' });
expect(result.name).toBe('SC Kopie');
expect(result.components[0].name).toBe('unbenannt');
expect(result.components[0].id).not.toBe(componentId.toString());
expect(source.components[0].name).toBe('');
expect(save).toHaveBeenCalledTimes(1);
} finally {
save.mockRestore();
find.mockRestore();
}
});
});
+1 -1
View File
@@ -42,7 +42,7 @@ export class UnitsService {
componentId: { $in: source.components.map((component) => component._id!) }, componentId: { $in: source.components.map((component) => component._id!) },
}).exec(); }).exec();
const components = source.components.map((component) => ({ const components = source.components.map((component) => ({
_id: componentIds.get(component._id!.toString()), name: component.name, type: component.type, _id: componentIds.get(component._id!.toString()), name: component.name || 'unbenannt', type: component.type,
prefix: component.prefix, postfix: component.postfix, index: component.index, properties: component.properties, prefix: component.prefix, postfix: component.postfix, index: component.index, properties: component.properties,
})); }));
const signals = sourceSignals.map((signal) => new this.signalModel({ const signals = sourceSignals.map((signal) => new this.signalModel({
+2
View File
@@ -1,4 +1,5 @@
import { DigitalOpcModule } from './digital-opc/digital-opc.module'; import { DigitalOpcModule } from './digital-opc/digital-opc.module';
import { AnlagePdfModule } from './anlagen/pdf/anlage-pdf.module';
import { StructuresModule } from './opcua-structures/structures.module'; import { StructuresModule } from './opcua-structures/structures.module';
import { OpcModule } from './opcua/opcua.module'; import { OpcModule } from './opcua/opcua.module';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
@@ -20,6 +21,7 @@ import { VisualisierungModule } from './visualisierung/visualisierung.module';
@Module({ @Module({
imports: [ imports: [
AnlagePdfModule,
BackupModule, BackupModule,
IoDiagnosticsModule, IoDiagnosticsModule,
SimulationModule, SimulationModule,
+2
View File
@@ -4,6 +4,8 @@ import { DrawData, DrawDataDto, DrawDto, DrawParameterDto, DrawShapeOptionenDto
// Öffentliche Grafiknamen werden ausschließlich auf bekannte Service-Methoden abgebildet. // Öffentliche Grafiknamen werden ausschließlich auf bekannte Service-Methoden abgebildet.
const graphicMethods = { const graphicMethods = {
text: 'text',
endschalter: 'endschalter',
gurtfoerderer: 'gurtfoerderer', setzmaschine: 'setzmaschine', band: 'band', gurtfoerderer: 'gurtfoerderer', setzmaschine: 'setzmaschine', band: 'band',
brecher: 'brecher', behaelter: 'behaelter', sieb: 'sieb', brecher: 'brecher', behaelter: 'behaelter', sieb: 'sieb',
siebentwaesserung: 'siebentwaesserung', weiche: 'weiche', zyklon: 'zyklon', siebentwaesserung: 'siebentwaesserung', weiche: 'weiche', zyklon: 'zyklon',
+4
View File
@@ -20,6 +20,8 @@ import { DrawVentil } from 'src/graphics/elements/drawVentil';
import { DrawWasserZufuhr } from 'src/graphics/elements/drawWasserZufuhr'; import { DrawWasserZufuhr } from 'src/graphics/elements/drawWasserZufuhr';
import { DrawBehaelterMulti } from 'src/graphics/elements/drawBehaelterMulti'; import { DrawBehaelterMulti } from 'src/graphics/elements/drawBehaelterMulti';
import { DrawMotor } from 'src/graphics/elements/drawMotor'; import { DrawMotor } from 'src/graphics/elements/drawMotor';
import { DrawEndschalter } from '../graphics/elements/drawEndschalter';
import { DrawText } from '../graphics/elements/drawText';
import { DrawPunkt } from '../graphics/elements/drawPunkt'; import { DrawPunkt } from '../graphics/elements/drawPunkt';
import { DrawRechteck } from '../graphics/elements/drawRechteck'; import { DrawRechteck } from '../graphics/elements/drawRechteck';
import { DrawAnlageDurmin } from 'src/graphics/elements/drawAnlageDurmin2'; import { DrawAnlageDurmin } from 'src/graphics/elements/drawAnlageDurmin2';
@@ -31,6 +33,8 @@ import { DrawFahrwagenOben } from '../graphics/elements/drawFahrwagenOben';
imports: [], imports: [],
controllers: [DrawController], controllers: [DrawController],
providers: [ providers: [
DrawText,
DrawEndschalter,
DrawPunkt, DrawPunkt,
DrawRechteck, DrawRechteck,
DrawFahrwagenOben, DrawFahrwagenOben,
+21
View File
@@ -1,5 +1,8 @@
import { Injectable, NotFoundException } from '@nestjs/common'; import { Injectable, NotFoundException } from '@nestjs/common';
import { parseMotorRequest } from '../_dto/motor.dto'; import { parseMotorRequest } from '../_dto/motor.dto';
import { parseTextRequest } from '../_dto/text.dto';
import { DrawText } from '../graphics/elements/drawText';
import { parseEndschalterRequest } from '../_dto/endschalter.dto';
import { parsePunktRequest } from '../_dto/punkt.dto'; import { parsePunktRequest } from '../_dto/punkt.dto';
import { DrawPunkt } from '../graphics/elements/drawPunkt'; import { DrawPunkt } from '../graphics/elements/drawPunkt';
import { DrawRechteck } from '../graphics/elements/drawRechteck'; import { DrawRechteck } from '../graphics/elements/drawRechteck';
@@ -31,6 +34,7 @@ import { DrawVentil } from 'src/graphics/elements/drawVentil';
import { DrawWasserZufuhr } from 'src/graphics/elements/drawWasserZufuhr'; import { DrawWasserZufuhr } from 'src/graphics/elements/drawWasserZufuhr';
import { DrawBehaelterMulti } from 'src/graphics/elements/drawBehaelterMulti'; import { DrawBehaelterMulti } from 'src/graphics/elements/drawBehaelterMulti';
import { DrawMotor } from 'src/graphics/elements/drawMotor'; import { DrawMotor } from 'src/graphics/elements/drawMotor';
import { DrawEndschalter } from '../graphics/elements/drawEndschalter';
import { DrawAnlageDurmin } from 'src/graphics/elements/drawAnlageDurmin2'; import { DrawAnlageDurmin } from 'src/graphics/elements/drawAnlageDurmin2';
import { DrawBandOben } from '../graphics/elements/drawBandOben'; import { DrawBandOben } from '../graphics/elements/drawBandOben';
import { parseBandObenRequest } from '../_dto/band-oben.dto'; import { parseBandObenRequest } from '../_dto/band-oben.dto';
@@ -63,6 +67,8 @@ export class DrawService {
private readonly buildFahrwagenOben: DrawFahrwagenOben, private readonly buildFahrwagenOben: DrawFahrwagenOben,
private readonly buildPunkt: DrawPunkt, private readonly buildPunkt: DrawPunkt,
private readonly buildRechteck: DrawRechteck, private readonly buildRechteck: DrawRechteck,
private readonly buildEndschalter: DrawEndschalter,
private readonly buildText: DrawText,
@@ -79,6 +85,14 @@ export class DrawService {
renderGraphic(type: string, input: unknown) { renderGraphic(type: string, input: unknown) {
switch (type) { switch (type) {
case 'text': {
const { config, options } = parseTextRequest(input);
return this.buildText.getObject(config, options);
}
case 'endschalter': {
const { config, options } = parseEndschalterRequest(input);
return this.buildEndschalter.getObject(config, options);
}
case 'rechteck': { case 'rechteck': {
const { config, options } = parseRechteckRequest(input); const { config, options } = parseRechteckRequest(input);
return this.buildRechteck.getObject(config, options); return this.buildRechteck.getObject(config, options);
@@ -199,6 +213,13 @@ export class DrawService {
rechteck(options?: DrawShapeOptionenDto, rawSvg?: boolean) { rechteck(options?: DrawShapeOptionenDto, rawSvg?: boolean) {
return rawSvg ? this.buildRechteck.getSvg(options) : this.buildRechteck.getDrawObject(options); return rawSvg ? this.buildRechteck.getSvg(options) : this.buildRechteck.getDrawObject(options);
} }
endschalter(options?: DrawShapeOptionenDto, rawSvg?: boolean) {
return rawSvg ? this.buildEndschalter.getSvg(options) : this.buildEndschalter.getDrawObject(options);
}
text(options?: DrawShapeOptionenDto, rawSvg?: boolean) {
return rawSvg ? this.buildText.getSvg(options) : this.buildText.getDrawObject(options);
}
punkt(options?: DrawShapeOptionenDto, rawSvg?: boolean) { punkt(options?: DrawShapeOptionenDto, rawSvg?: boolean) {
return rawSvg ? this.buildPunkt.getSvg(options) : this.buildPunkt.getDrawObject(options); return rawSvg ? this.buildPunkt.getSvg(options) : this.buildPunkt.getDrawObject(options);
} }
@@ -0,0 +1,65 @@
import { DrawEndschalter } from './drawEndschalter';
import { parseEndschalterRequest } from '../../_dto/endschalter.dto';
describe('DrawEndschalter', () => {
const generator = new DrawEndschalter();
it.each([
['unten', 20, 40, 'M 4 31', 'M 4,31'],
['oben', 20, 40, 'M 16 9', 'M 16,9'],
['rechts', 40, 20, 'M 31 16', 'M 31,16'],
['links', 40, 20, 'M 9 4', 'M 9,4'],
] as const)('richtet die Erfassungsbögen nach %s aus und passt den Zeichenbereich an', (direction, width, height, svgStart, xamlStart) => {
const result = generator.getObject({ scale: 2, raster: 4 }, { direction });
expect([result.width, result.height]).toEqual([width, height]);
for (const variant of result.varianten) {
expect(variant.svg).toContain(svgStart);
expect(variant.xaml).toContain(xamlStart);
}
const legacy = generator.getDrawObject({ direction });
expect([legacy.px_width, legacy.px_height]).toEqual([width, height]);
expect([legacy.length, legacy.height]).toEqual([width / 8, height / 8]);
});
it('behält unten als Standard und validiert die neue Option', () => {
expect(parseEndschalterRequest({ config: {} }).options.direction).toBe('unten');
expect(() => parseEndschalterRequest({ config: {}, options: { direction: 'diagonal' } })).toThrow();
expect(() => parseEndschalterRequest({ config: {}, options: { typo: 'oben' } })).toThrow();
});
it('liefert das schlanke Symbol mit drei Zuständen als SVG und XAML', () => {
const result = generator.getObject({ scale: 2, raster: 4 });
expect(result.name).toBe('endschalter');
expect(result.width).toBe(20);
expect(result.height).toBe(40);
expect(result.varianten.map(variant => variant.state)).toEqual(['inactive', 'active', 'error']);
for (const variant of result.varianten) {
expect(variant.svg).toContain('<svg xmlns=');
expect(variant.xaml).toContain('<Viewbox xmlns=');
expect(variant.svg.match(/<path /g)).toHaveLength(4);
expect(variant.xaml.match(/<Path /g)).toHaveLength(4);
expect(variant.svg).not.toMatch(/NaN|Infinity|undefined/);
expect(Buffer.from(variant.xamlBase64, 'base64').toString('utf8')).toBe(variant.xaml);
}
expect(result.varianten[1].svg).toContain('#00f000');
expect(result.varianten[2].xaml).toContain('#f00000');
});
it('skaliert Körper und Bögen und übernimmt die Zustandsfarben', () => {
const config = { scale: 4, raster: 4 };
const result = generator.getObject(config, { colorActive: '#123456' });
expect(result.width).toBe(40);
expect(result.height).toBe(80);
expect(result.varianten[1].svg).toContain('#123456');
expect(result.varianten[1].svg).toContain('stroke-width="2"');
expect(generator.getDrawObject({ state: 'active' }).px_height).toBe(40);
expect(generator.getSvg({ state: 'active', xaml: true })).toContain('<Viewbox');
});
it('verhindert ungültige Skalierungen und Farben', () => {
expect(() => generator.getObject({ scale: 0, raster: 4 })).toThrow();
expect(() => generator.getObject({ scale: 2, raster: 4 }, { colorActive: 'red' })).toThrow();
expect(() => generator.getObject({ scale: Number.MAX_VALUE / 4, raster: 1 })).toThrow();
});
});
+155
View File
@@ -0,0 +1,155 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import type { DrawDataDto, DrawDto, DrawShapeOptionenDto } from '../../_dto/draw.dto';
import { parseEndschalterRequest } from '../../_dto/endschalter.dto';
import { DrawGroup } from '../lib/drawGroup';
import { DrawHeader } from '../lib/drawHeader';
import { DrawPath } from '../lib/drawPath';
import type { PathCommand } from '../lib/types/path.types';
import type { GraphicGenerator } from './graphic-generator';
import type { EndschalterConfig, EndschalterOptions, EndschalterDirection } from './types';
@Injectable()
export class DrawEndschalter implements GraphicGenerator<EndschalterConfig, EndschalterOptions> {
private readonly defaultColors: EndschalterOptions = {
colorInactive: '#808080',
colorActive: '#00f000',
colorError: '#f00000',
};
/** Koordinaten direkt drehen, damit SVG und XAML dieselbe Geometrie erhalten. */
private orientPath(commands: PathCommand[], unit: number, direction: EndschalterDirection): PathCommand[] {
const width = 2.5 * unit;
const height = 5 * unit;
const point = (x: number, y: number) => {
switch (direction) {
case 'oben': return { x: width - x, y: height - y };
case 'rechts': return { x: y, y: width - x };
case 'links': return { x: height - y, y: x };
default: return { x, y };
}
};
return commands.map(command => {
if (command.type === 'Q') {
const control = point(command.x1, command.y1);
return { ...command, ...point(command.x, command.y), x1: control.x, y1: control.y };
}
if (command.type === 'M' || command.type === 'L') {
return { ...command, ...point(command.x, command.y) };
}
return command;
});
}
/** Abgerundeter Sensorkörper. Eine Einheit entspricht raster * scale. */
private createSensorBody(unit: number, color: string, direction: EndschalterDirection): DrawPath {
const left = 0.875 * unit;
const right = 1.625 * unit;
const top = unit;
const bottom = 3.125 * unit;
const radius = 0.125 * unit;
const outline: PathCommand[] = [
{ type: 'M', x: left + radius, y: top },
{ type: 'L', x: right - radius, y: top },
{ type: 'Q', x1: right, y1: top, x: right, y: top + radius },
{ type: 'L', x: right, y: bottom - radius },
{ type: 'Q', x1: right, y1: bottom, x: right - radius, y: bottom },
{ type: 'L', x: left + radius, y: bottom },
{ type: 'Q', x1: left, y1: bottom, x: left, y: bottom - radius },
{ type: 'L', x: left, y: top + radius },
{ type: 'Q', x1: left, y1: top, x: left + radius, y: top },
{ type: 'Z' },
];
const body = new DrawPath(this.orientPath(outline, unit, direction));
body.setAtrr({ fill: color, stroke: '#202020', strokeWidth: unit / 16 });
return body;
}
/** Drei nach unten gewölbte Erfassungsbögen wie in der Vorlage. */
private createDetectionArcs(unit: number, color: string, direction: EndschalterDirection): DrawPath[] {
const centerX = 1.25 * unit;
return [0, 1, 2].map(index => {
const halfWidth = (0.375 + index * 0.1875) * unit;
const top = (3.375 + index * 0.25) * unit;
const depth = (0.375 + index * 0.0625) * unit;
const arc = new DrawPath(this.orientPath([
{ type: 'M', x: centerX - halfWidth, y: top },
{ type: 'Q', x1: centerX, y1: top + depth, x: centerX + halfWidth, y: top },
], unit, direction));
arc.setAtrr({ fill: 'none', stroke: color, strokeWidth: unit / 8 });
return arc;
});
}
private create(unit: number, color: string, direction: EndschalterDirection): DrawGroup {
const group = new DrawGroup({});
group.add(this.createSensorBody(unit, color, direction));
for (const arc of this.createDetectionArcs(unit, color, direction)) {
group.add(arc);
}
return group;
}
getObject(config: EndschalterConfig, options?: Partial<EndschalterOptions>): DrawDataDto {
// Skalierung und Zustandsfarben verwenden die vorhandene Motor-Validierung.
const parsed = parseEndschalterRequest({ config, options });
const unit = parsed.config.scale * parsed.config.raster;
const direction = parsed.options.direction;
const horizontal = direction === 'links' || direction === 'rechts';
const width = (horizontal ? 5 : 2.5) * unit;
const height = (horizontal ? 2.5 : 5) * unit;
if (!Number.isFinite(width) || !Number.isFinite(height)) {
throw new BadRequestException('Die Endschalter-Abmessungen sind zu groß');
}
const colors = { ...this.defaultColors, ...parsed.options };
const states = [
{ state: 'inactive', color: colors.colorInactive },
{ state: 'active', color: colors.colorActive },
{ state: 'error', color: colors.colorError },
];
const varianten = states.map(({ state, color }) => {
const header = new DrawHeader({ lenght: width, height });
header.add(this.create(unit, color, direction));
const svg = header.getChildString(false, 0);
const xaml = header.getChildString(true, 0);
return { state, svg, xaml, xamlBase64: Buffer.from(xaml, 'utf8').toString('base64') };
});
return { name: 'endschalter', width, height, varianten };
}
private selectedVariant(options: DrawShapeOptionenDto = {}) {
const config = { scale: Number(options.scale ?? 2), raster: Number(options.raster ?? 4) };
const colors = {
direction: options.direction ?? 'unten',
colorInactive: options.colorInactive ?? this.defaultColors.colorInactive,
colorActive: options.colorActive ?? this.defaultColors.colorActive,
colorError: options.colorError ?? this.defaultColors.colorError,
};
const result = this.getObject(config, colors);
const variant = result.varianten.find(item => item.state === options.state) ?? result.varianten[0];
return { result, variant, config };
}
getDrawObject(options?: DrawShapeOptionenDto): DrawDto {
const { result, variant, config } = this.selectedVariant(options);
return {
name: result.name,
height: result.height / (config.raster * config.scale),
length: result.width / (config.raster * config.scale),
px_height: result.height,
px_width: result.width,
raster: config.raster,
scale: config.scale,
offset_x: 0,
offset_y: 0,
svg: variant.svg,
};
}
getSvg(options?: DrawShapeOptionenDto): string {
const { variant } = this.selectedVariant(options);
return options?.xaml ? variant.xaml : variant.svg;
}
}
+72
View File
@@ -0,0 +1,72 @@
import { DrawText } from './drawText';
import { parseTextRequest } from '../../_dto/text.dto';
describe('DrawText Grafikgenerator', () => {
const generator = new DrawText();
const config = { text: 'Anlage bereit', width: 160, height: 40, fontSize: 16 };
it('liefert inactive, active und error als vollständiges SVG und XAML', () => {
const result = generator.getObject(config);
expect(result.varianten.map(variant => variant.state)).toEqual(['inactive', 'active', 'error']);
expect([result.width, result.height]).toEqual([160, 40]);
for (const variant of result.varianten) {
expect(variant.svg).toContain('<svg xmlns=');
expect(variant.xaml).toContain('<Viewbox xmlns=');
expect(variant.svg).toContain('Anlage bereit');
expect(variant.xaml).toContain('Text="Anlage bereit"');
expect(Buffer.from(variant.xamlBase64, 'base64').toString('utf8')).toBe(variant.xaml);
expect(variant.svg).not.toContain('<path');
}
expect(result.varianten[0].svg).toContain('fill="#808080"');
expect(result.varianten[1].xaml).toContain('Foreground="#00f000"');
expect(result.varianten[2].svg).toContain('fill="#f00000"');
});
it('zeichnet den transparenten Rahmen hinter dem Text und innerhalb der Abmessungen', () => {
const result = generator.getObject(config, { frame: true, stroke: '#123456', strokeWidth: 2 });
for (const variant of result.varianten) {
expect(variant.svg).toContain('M 1 1');
expect(variant.svg).toContain('stroke="#123456"');
expect(variant.svg).toContain('fill="none"');
expect(variant.svg.indexOf('<path')).toBeLessThan(variant.svg.indexOf('<text'));
expect(variant.xaml.indexOf('<Path')).toBeLessThan(variant.xaml.indexOf('<TextBlock'));
expect(variant.xaml).not.toContain('Fill="none"');
}
});
it('unterstützt Füllfarbe ohne Rahmen und eigene Zustandsfarben', () => {
const result = generator.getObject(config, { frame: false, fill: '#ffffff', colorActive: '#123456' });
expect(result.varianten[1].svg).toContain('fill="#ffffff"');
expect(result.varianten[1].svg).toContain('stroke-width="0"');
expect(result.varianten[1].xaml).toContain('Foreground="#123456"');
});
it('maskiert Textzeichen in beiden Formaten und lässt keine XML-Elemente einschleusen', () => {
const result = generator.getObject({ ...config, text: 'A & B <Text> "Zitat"' });
for (const variant of result.varianten) {
expect(variant.svg).toContain('A &amp; B &lt;Text&gt; &quot;Zitat&quot;');
expect(variant.xaml).toContain('A &amp; B &lt;Text&gt; &quot;Zitat&quot;');
expect(variant.xaml).not.toContain('<Text>');
}
});
it('ordnet mehrzeiligen Text an und hält lange Texte durch kleinere Schrift im Rahmen', () => {
const result = generator.getObject({ ...config, text: 'Erste Zeile\r\nZweite Zeile mit langem Text', fontSize: 60 });
const svg = result.varianten[0].svg;
expect(svg.match(/<text /g)).toHaveLength(2);
const sizes = [...svg.matchAll(/font-size="([\d.]+)"/g)].map(match => Number(match[1]));
expect(sizes.every(size => size > 0 && size < 60)).toBe(true);
expect(svg).not.toMatch(/NaN|Infinity|undefined/);
});
it('validiert Parameter und erhält die bisherigen Zeichen-API-Konventionen', () => {
expect(parseTextRequest({ config: {} }).config.text).toBe('Text');
expect(() => parseTextRequest({ config: { fontSize: 0 } })).toThrow();
expect(() => parseTextRequest({ config: { text: '\u0000' } })).toThrow();
expect(() => parseTextRequest({ config: {}, options: { frame: 'true' } })).toThrow();
expect(() => parseTextRequest({ config: {}, options: { colorActive: 'green' } })).toThrow();
expect(() => parseTextRequest({ config: {}, options: { frame: true, strokeWidth: 100 } })).toThrow();
expect(generator.getDrawObject({ text: 'Test' }).name).toBe('text');
expect(generator.getSvg({ text: 'Test', xaml: true })).toContain('Text="Test"');
});
});
+107
View File
@@ -0,0 +1,107 @@
import { Injectable } from '@nestjs/common';
import type { DrawDataDto, DrawDto, DrawShapeOptionenDto } from '../../_dto/draw.dto';
import { parseTextRequest } from '../../_dto/text.dto';
import { DrawGroup } from '../lib/drawGroup';
import { DrawHeader } from '../lib/drawHeader';
import { DrawPath } from '../lib/drawPath';
import { DrawText as TextElement } from '../lib/drawText';
import type { GraphicGenerator } from './graphic-generator';
import type { TextConfig, TextOptions } from './types';
@Injectable()
export class DrawText implements GraphicGenerator<TextConfig, TextOptions> {
private createBackground(config: TextConfig, options: TextOptions): DrawPath {
const inset = options.strokeWidth / 2;
const background = new DrawPath([
{ type: 'M', x: inset, y: inset },
{ type: 'L', x: config.width - inset, y: inset },
{ type: 'L', x: config.width - inset, y: config.height - inset },
{ type: 'L', x: inset, y: config.height - inset },
{ type: 'Z' },
]);
background.setAtrr({
stroke: options.stroke === 'none' ? '#000000' : options.stroke,
strokeWidth: options.strokeWidth,
fill: options.fill === 'transparent' ? 'none' : options.fill,
});
return background;
}
private createText(config: TextConfig, options: TextOptions, color: string): DrawGroup {
const group = new DrawGroup({});
const lines = config.text.replace(/\r\n?/g, '\n').split('\n');
const padding = Math.min(4 + options.strokeWidth, config.width / 4, config.height / 4);
const availableWidth = config.width - padding * 2;
const availableHeight = config.height - padding * 2;
const longestLine = Math.max(1, ...lines.map(line => Array.from(line).length));
// Schrift bei langen oder mehrzeiligen Texten innerhalb der Zeichenfläche halten.
const fontSize = Math.min(config.fontSize, availableWidth / (longestLine * 0.75), availableHeight / (lines.length * 1.25));
const lineHeight = fontSize * 1.25;
const top = (config.height - lines.length * lineHeight) / 2;
lines.forEach((text, index) => {
group.add(new TextElement({
x: padding,
y: top + index * lineHeight,
text,
centeredBox: { width: availableWidth, height: lineHeight, fontSize, color },
}));
});
return group;
}
private create(config: TextConfig, options: TextOptions, color: string): DrawHeader {
const group = new DrawGroup({});
// DrawGroup gibt Elemente in umgekehrter Reihenfolge aus: Hintergrund zuerst zeichnen.
group.add(this.createText(config, options, color));
if (options.frame || options.fill !== 'transparent') group.add(this.createBackground(config, options));
const header = new DrawHeader({ lenght: config.width, height: config.height });
header.add(group);
return header;
}
getObject(config: TextConfig, options?: Partial<TextOptions>): DrawDataDto {
const parsed = parseTextRequest({ config, options });
const states = [
{ state: 'inactive', color: parsed.options.colorInactive },
{ state: 'active', color: parsed.options.colorActive },
{ state: 'error', color: parsed.options.colorError },
];
const varianten = states.map(({ state, color }) => {
const header = this.create(parsed.config, parsed.options, color);
const svg = header.getChildString(false, 0);
const xaml = header.getChildString(true, 0);
return { state, svg, xaml, xamlBase64: Buffer.from(xaml, 'utf8').toString('base64') };
});
return { name: 'text', width: parsed.config.width, height: parsed.config.height, varianten };
}
private selectedVariant(options: DrawShapeOptionenDto = {}) {
const parsed = parseTextRequest({
config: { text: options.text ?? 'Text', width: Number(options.width ?? 120), height: Number(options.height ?? 40), fontSize: Number(options.fontSize ?? 16) },
options: {
frame: options.frame === undefined ? false : String(options.frame) === 'true',
...(options.stroke !== undefined ? { stroke: options.stroke } : {}),
...(options.strokeWidth !== undefined ? { strokeWidth: Number(options.strokeWidth) } : {}),
...(options.fill !== undefined ? { fill: options.fill } : {}),
...(options.colorInactive !== undefined ? { colorInactive: options.colorInactive } : {}),
...(options.colorActive !== undefined ? { colorActive: options.colorActive } : {}),
...(options.colorError !== undefined ? { colorError: options.colorError } : {}),
},
});
const result = this.getObject(parsed.config, parsed.options);
const variant = result.varianten.find(item => item.state === options.state) ?? result.varianten[0];
return { result, variant };
}
getDrawObject(options?: DrawShapeOptionenDto): DrawDto {
const { result, variant } = this.selectedVariant(options);
return { name: result.name, height: result.height, length: result.width, px_height: result.height, px_width: result.width,
raster: 1, scale: 1, offset_x: 0, offset_y: 0, svg: variant.svg };
}
getSvg(options?: DrawShapeOptionenDto): string {
const { variant } = this.selectedVariant(options);
return options?.xaml ? variant.xaml : variant.svg;
}
}
+13
View File
@@ -17,7 +17,20 @@ export interface MotorConfig {
raster: number; raster: number;
} }
export interface EndschalterConfig extends MotorConfig {}
export type EndschalterDirection = 'oben' | 'unten' | 'rechts' | 'links';
export interface EndschalterOptions extends MotorOptions {
direction?: EndschalterDirection;
}
export interface PunktConfig { scale: number; raster: number } export interface PunktConfig { scale: number; raster: number }
export interface TextConfig { text: string; width: number; height: number; fontSize: number }
export interface TextOptions extends MotorOptions {
frame: boolean;
stroke: string;
strokeWidth: number;
fill: string;
}
export interface PunktOptions { colorInactive: string; colorActive: string } export interface PunktOptions { colorInactive: string; colorActive: string }
export interface RechteckConfig { width: number; height: number } export interface RechteckConfig { width: number; height: number }
export interface RechteckOptions { stroke: string; strokeWidth: number; fill: string } export interface RechteckOptions { stroke: string; strokeWidth: number; fill: string }
+9 -5
View File
@@ -5,7 +5,7 @@ interface PropText {
x: number, x: number,
y: number, y: number,
text:string text:string
centeredBox?: { width: number; height: number; fontSize: number }; centeredBox?: { width: number; height: number; fontSize: number; color?: string };
} }
interface SvgOptions { interface SvgOptions {
@@ -18,6 +18,10 @@ interface SvgOptions {
export class DrawText extends DrawElement { export class DrawText extends DrawElement {
private escapeText(value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&apos;');
}
@@ -40,13 +44,13 @@ export class DrawText extends DrawElement {
drawSvg() { drawSvg() {
const box = this.posAndText.centeredBox; const box = this.posAndText.centeredBox;
if (box) { 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>`; 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="${box.color ?? '#000000'}">${this.escapeText(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);
const shape = this.drawElementSvg(posStr,this.posAndText.text, paraStr); const shape = this.drawElementSvg(posStr,this.escapeText(this.posAndText.text), paraStr);
return shape; return shape;
} }
@@ -54,14 +58,14 @@ export class DrawText extends DrawElement {
drawXaml(): string { drawXaml(): string {
const box = this.posAndText.centeredBox; const box = this.posAndText.centeredBox;
if (box) { 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>`; return `<Grid Canvas.Left="${this.posAndText.x}" Canvas.Top="${this.posAndText.y}" Width="${box.width}" Height="${box.height}"><TextBlock Text="${this.escapeText(this.posAndText.text)}" FontFamily="Arial" FontSize="${box.fontSize}" FontWeight="Bold" Foreground="${box.color ?? '#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);
const shape = this.drawElementXaml(this.posAndText.x,this.posAndText.y,this.posAndText.text, paraStr); const shape = this.drawElementXaml(this.posAndText.x,this.posAndText.y,this.escapeText(this.posAndText.text), paraStr);
return shape; return shape;
} }
+5 -2
View File
@@ -98,10 +98,13 @@ export class MotorOpcService {
const extras: {operatingMode:MotorBinding['operatingMode'];parameters:MotorBinding['parameters'];extraIssues:string[]}={operatingMode:null,parameters:null,extraIssues:[]}; const extras: {operatingMode:MotorBinding['operatingMode'];parameters:MotorBinding['parameters'];extraIssues:string[]}={operatingMode:null,parameters:null,extraIssues:[]};
for(const role of ['operatingMode','parameters'] as const){const ref=binding?.[role];if(ref){try{const definition=definitions.structures.find(s=>s.name===ref.name);if(!definition)throw new Error();checkMotorExtra(definition,ref.id,role);extras[role]=ref;}catch{extras.extraIssues.push(role+'-Zuordnung ungültig');}}} for(const role of ['operatingMode','parameters'] as const){const ref=binding?.[role];if(ref){try{const definition=definitions.structures.find(s=>s.name===ref.name);if(!definition)throw new Error();checkMotorExtra(definition,ref.id,role);extras[role]=ref;}catch{extras.extraIssues.push(role+'-Zuordnung ungültig');}}}
const graphics = (view?.elemente ?? []).flatMap(e => { const graphics = (view?.elemente ?? []).flatMap(e => {
if (!e.show) return [];
if(e.darstellung === 'standard' && !['motor','betriebsart','anfahrzeit'].includes(e.typ))return []; if(e.darstellung === 'standard' && !['motor','betriebsart','anfahrzeit'].includes(e.typ))return [];
const kind=e.typ==='betriebsart'?'operatingMode':e.typ==='anfahrzeit'?'startTime':'motor'; const warning = e.darstellung === 'xaml' && (e.generator?.grafikTyp === 'warnung' || e.key.toLowerCase().startsWith('warnung'));
const kind=e.typ==='betriebsart'?'operatingMode':e.typ==='anfahrzeit'?'startTime':
e.darstellung === 'xaml' && !warning && !['motor','bandOben','fahrwagenOben','fahrbandOben'].includes(e.generator?.grafikTyp ?? e.typ) ? 'static' : 'motor';
const variants = e.darstellung === 'xaml' ? e.varianten : kind!=='motor'?[]:this.draw.renderGraphic('motor',{config:{},options:{}}).varianten.map(v=>({zustand:v.state,svg:v.svg})); const variants = e.darstellung === 'xaml' ? e.varianten : kind!=='motor'?[]:this.draw.renderGraphic('motor',{config:{},options:{}}).varianten.map(v=>({zustand:v.state,svg:v.svg}));
return [{ key:e.key, kind, placement:{x:e.posX,y:e.posY,width:e.width,height:e.height,z:e.zIndex}, variants: variants.map(v=>({state:v.zustand,svg:v.svg??''})) }]; return [{ key:e.key, kind, warning, placement:{x:e.posX,y:e.posY,width:e.width,height:e.height,z:e.zIndex}, variants: variants.map(v=>({state:v.zustand,svg:v.svg??''})) }];
}); });
return { componentId:c.componentId, name:c.name, antriebId:c.antriebId, structure, control:binding?.control??null, revision:binding?.revision??0, field:binding?.field??'M1', issue, graphics, ...extras }; return { componentId:c.componentId, name:c.name, antriebId:c.antriebId, structure, control:binding?.control??null, revision:binding?.revision??0, field:binding?.field??'M1', issue, graphics, ...extras };
}); });
+12
View File
@@ -8,6 +8,18 @@ jest.mock('../draw/draw.service',()=>({DrawService:class{}}));
import {motorStatus} from './motor-status'; import {motorStatus} from './motor-status';
import {checkMotorControl,motorCommands,checkMotorExtra,checkMotorField,MotorOpcService} from './motor-opc.service'; import {checkMotorControl,motorCommands,checkMotorExtra,checkMotorField,MotorOpcService} from './motor-opc.service';
describe('Motor OPC',()=>{ describe('Motor OPC',()=>{
it('includes visible static graphics independently of motor bindings and keeps warnings dynamic',async()=>{
const element=(key:string,grafikTyp:string,show=true)=>({key,typ:key,darstellung:'xaml',show,posX:10,posY:20,width:30,height:40,zIndex:2,
generator:{grafikTyp},varianten:[{zustand:'default',svg:'<svg/>'}]});
const service=new MotorOpcService({} as any,{} as any,
{findAll:async()=>[{componentId:'c',elemente:[element('zusatz','rechteck'),element('meldung','warnung'),element('versteckt','punkt',false)]}]} as any,
{list:async()=>({anlageId:'a',structures:[]})} as any,{} as any,{} as any,{} as any);
jest.spyOn(service,'list').mockResolvedValue({anlageId:'a',components:[{componentId:'c',name:'Motor',antriebId:1}],bindings:[]} as any);
const [row]=await service.scene();
expect(row.graphics).toHaveLength(2);
expect(row.graphics[0]).toMatchObject({key:'zusatz',kind:'static',warning:false,variants:[{state:'default',svg:'<svg/>'}]});
expect(row.graphics[1]).toMatchObject({key:'meldung',kind:'motor',warning:true});
});
it('writes each motor command once as true and rechecks the binding before writing',async()=>{ it('writes each motor command once as true and rechecks the binding before writing',async()=>{
const definition:any={id:'control',name:'Control_0',version:1,direction:'write',fields:motorCommands.map(name=>({name,dataType:'Boolean',writable:true}))}; const definition:any={id:'control',name:'Control_0',version:1,direction:'write',fields:motorCommands.map(name=>({name,dataType:'Boolean',writable:true}))};
const binding={revision:2,control:{id:'control',name:'Control_0'}}; const binding={revision:2,control:{id:'control',name:'Control_0'}};
@@ -5,6 +5,24 @@ jest.mock('../visualisierungen/visualisierungen.service', () => ({ Visualisierun
import { AggregateMappingService } from './aggregate-mapping.service'; import { AggregateMappingService } from './aggregate-mapping.service';
describe('Zuordnung übernehmen', () => { describe('Zuordnung übernehmen', () => {
it('liefert gespeicherte Querverweise nur für die aktive Anlage und Verbindung ohne SQL-Abfragen', async () => {
const aggregateId = new Types.ObjectId();
const componentId = new Types.ObjectId();
const orphanId = new Types.ObjectId();
const query = (value: unknown) => ({ lean: () => ({ exec: async () => value }) });
const mappings = { find: jest.fn(() => query([
{ visuAggregateId: aggregateId, proConAggregateId: 70, spsAntriebId: 3 },
{ visuAggregateId: orphanId, proConAggregateId: 71, spsAntriebId: 4 },
])) };
const local = { find: jest.fn(() => query([{ _id: aggregateId, componentId, antriebId: 3, antriebName: 'Verteilband' }])) };
const service = new AggregateMappingService({} as any, local as any, {} as any, mappings as any, {} as any, {} as any);
jest.spyOn(service as any, 'context').mockResolvedValue({ anlageId: 'anlage', verbindungId: 'test-db', verbindungName: 'Test' });
const result = await service.savedLinks();
expect(mappings.find).toHaveBeenCalledWith({ anlageId: 'anlage', verbindungId: 'test-db' });
expect(local.find).toHaveBeenCalledWith(expect.objectContaining({ $expr: { $eq: [{ $toString: '$anlageId' }, 'anlage'] } }));
expect(result.links).toEqual([{ proConAggregateId: 70, spsAntriebId: 3, visuAggregateId: aggregateId.toString(),
componentId: componentId.toString(), localName: 'Verteilband', localSpsAntriebId: 3 }]);
});
function setup() { function setup() {
const updateOne = jest.fn<() => Promise<{ upsertedCount: number }>>().mockResolvedValue({ upsertedCount: 1 }); 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 service = new AggregateMappingService({} as any, {} as any, {} as any, { updateOne } as any, {} as any, {} as any);
@@ -52,6 +52,22 @@ export class AggregateMappingService {
return { anlageId: anlage._id.toString(), verbindungId: verbindung._id.toString(), verbindungName: verbindung.name }; return { anlageId: anlage._id.toString(), verbindungId: verbindung._id.toString(), verbindungName: verbindung.name };
} }
async savedLinks() {
const context = await this.context();
const mappings = await this.mappings.find({ anlageId: context.anlageId, verbindungId: context.verbindungId }).lean().exec();
const aggregates = await this.local.find({
_id: { $in: mappings.map(mapping => mapping.visuAggregateId) },
$expr: { $eq: [{ $toString: '$anlageId' }, context.anlageId] },
}).lean().exec();
return { ...context, links: mappings.flatMap(mapping => {
const aggregate = aggregates.find(item => item._id.toString() === mapping.visuAggregateId.toString());
if (!aggregate || !Number.isSafeInteger(mapping.proConAggregateId)) return [];
return [{ proConAggregateId: mapping.proConAggregateId, spsAntriebId: mapping.spsAntriebId,
visuAggregateId: aggregate._id.toString(), componentId: aggregate.componentId.toString(),
localName: aggregate.antriebName, localSpsAntriebId: aggregate.antriebId }];
}) };
}
async preview() { async preview() {
const context = await this.context(); const context = await this.context();
const [sources, local, stored] = await Promise.all([ const [sources, local, stored] = await Promise.all([
@@ -29,6 +29,9 @@ export class AggregateController {
@Get('zuordnung') @Get('zuordnung')
preview() { return this.mapping.preview(); } preview() { return this.mapping.preview(); }
@Get('zuordnung/gespeichert')
savedLinks() { return this.mapping.savedLinks(); }
@Post('zuordnung/reparieren') @Post('zuordnung/reparieren')
@HttpCode(200) @HttpCode(200)
repairMapping(@Body() dto: RepairMappingRequest) { return this.mapping.repair(dto); } repairMapping(@Body() dto: RepairMappingRequest) { return this.mapping.repair(dto); }
@@ -1,10 +1,14 @@
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; import { Body, Controller, Delete, Get, Param, Patch, Post, Put } from '@nestjs/common';
import { GraphicLibraryService } from './graphic-library.service'; import { GraphicLibraryService } from './graphic-library.service';
import type { GrafikGeneratorDaten } from '../shared/graphic.types'; import type { GrafikGeneratorDaten } from '../shared/graphic.types';
@Controller('visualisierung/grafik-bibliothek') @Controller('visualisierung/grafik-bibliothek')
export class GraphicLibraryController { export class GraphicLibraryController {
constructor(private readonly library: GraphicLibraryService) {} constructor(private readonly library: GraphicLibraryService) {}
@Get() list() { return this.library.list(); } @Get() list() { return this.library.list(); }
@Patch(':id/name')
rename(@Param('id') id: string, @Body() input: { anlageId: string; version: number; name: string }) {
return this.library.rename(id, input);
}
@Put(':id') update(@Param('id') id: string, @Body() input: { anlageId: string; version: number; generator: GrafikGeneratorDaten; variant: string }) { return this.library.update(id, input); } @Put(':id') update(@Param('id') id: string, @Body() input: { anlageId: string; version: number; generator: GrafikGeneratorDaten; variant: string }) { return this.library.update(id, input); }
@Post() create(@Body() input: { anlageId: string; name: string; generator: GrafikGeneratorDaten; variant: string }) { return this.library.create(input); } @Post() create(@Body() input: { anlageId: string; name: string; generator: GrafikGeneratorDaten; variant: string }) { return this.library.create(input); }
@Post('xaml') export(@Body() input: { anlageId: string }) { return this.library.exportXaml(input?.anlageId); } @Post('xaml') export(@Body() input: { anlageId: string }) { return this.library.exportXaml(input?.anlageId); }
@@ -8,7 +8,7 @@ import { GraphicLibraryController } from './graphic-library.controller';
export const LibrarySchema = new Schema({ export const LibrarySchema = new Schema({
anlageId: { type: String, required: true, immutable: true }, anlageId: { type: String, required: true, immutable: true },
name: { type: String, required: true, immutable: true }, nameKey: { type: String, required: true, immutable: true }, name: { type: String, required: true }, nameKey: { type: String, required: true },
revision: { type: Number, default: 0 }, revision: { type: Number, default: 0 },
variant: { type: String, required: true }, variant: { type: String, required: true },
generator: { type: Schema.Types.Mixed, required: true }, generator: { type: Schema.Types.Mixed, required: true },
@@ -92,6 +92,44 @@ export class GraphicLibraryService {
if (!doc) throw new NotFoundException('Bibliotheksgrafik dieser Anlage nicht gefunden'); if (!doc) throw new NotFoundException('Bibliotheksgrafik dieser Anlage nicht gefunden');
return this.output(doc); return this.output(doc);
} }
async rename(id: string, input: { anlageId: string; version: number; name: string }): Promise<LibraryGraphic> {
const anlageId = (await this.anlagen.getSelected()).id;
if (!input || input.anlageId !== anlageId) throw new BadRequestException('Anlage geändert. Neu laden.');
await this.find(id, anlageId);
if (!Number.isSafeInteger(input.version) || input.version < 0) throw new BadRequestException('Ungültige Version');
const name = normalizeGraphicName(input.name);
if (!name) throw new BadRequestException('Grafikname fehlt');
let doc: any;
try {
doc = await this.model.findOneAndUpdate({ _id: id, anlageId,
...(input.version === 0 ? { $or: [{ revision: 0 }, { revision: { $exists: false } }] } : { revision: input.version }) },
{ $set: { name, nameKey: name.toLowerCase() }, $inc: { revision: 1 } },
{ new: true, runValidators: true }).lean().exec();
} catch (error) {
if ((error as { code?: number }).code === 11000) {
throw new BadRequestException('Dieser Grafikname ist in der Bibliothek bereits vergeben.');
}
throw error;
}
if (!doc) throw new ConflictException('Grafik wurde inzwischen geändert. Bibliothek neu laden.');
// Nur Namen in den ID-basierten Verknüpfungen ändern, eingefrorene Grafikdaten erhalten.
for (const collection of ['anzeigewerte', 'sensoren_analog', 'sensoren_digital']) {
await this.connection.collection(collection).updateMany({ anlageId, 'rows.graphics.libraryId': id }, {
$set: {
'rows.$[].graphics.$[graphic].name': name,
'rows.$[].graphics.$[graphic].generator.ergebnis.name': name,
},
$inc: { revision: 1 },
}, { arrayFilters: [{ 'graphic.libraryId': id }] });
}
await this.connection.collection('proConViewAggregate').updateMany({ 'elemente.varianten.libraryId': id }, {
$set: { 'elemente.$[element].varianten.$[variant].libraryName': name },
$inc: { __v: 1 },
}, { arrayFilters: [{ 'element.varianten.libraryId': id }, { 'variant.libraryId': id }] });
return this.output(doc);
}
async resolveTable<T extends { anlageId: string; rows: { graphics: GraphicBinding[] }[] }>(table: T): Promise<T> { async resolveTable<T extends { anlageId: string; rows: { graphics: GraphicBinding[] }[] }>(table: T): Promise<T> {
const cache = new Map<string, LibraryGraphic>(); const cache = new Map<string, LibraryGraphic>();
const rows = [] as T['rows']; const rows = [] as T['rows'];
@@ -18,7 +18,7 @@ describe('Feste Grafikbibliothek', () => {
const variant = rendered.varianten[1]; const variant = rendered.varianten[1];
asset = { _id: id, anlageId: 'a1', name: 'Punkt_gruen', variant: 'active', generator: input.generator, asset = { _id: id, anlageId: 'a1', name: 'Punkt_gruen', variant: 'active', generator: input.generator,
width: 24, height: 24, svg: variant.svg, xaml: variant.xaml, xamlBase64: variant.xamlBase64 }; width: 24, height: 24, svg: variant.svg, xaml: variant.xaml, xamlBase64: variant.xamlBase64 };
model = { create: jest.fn(async data => ({ ...data, _id: id })), findOne: jest.fn(() => ({ lean: () => ({ exec: async () => asset }) })), model = { create: jest.fn(async (data: Record<string, unknown>) => ({ ...data, _id: id })), findOne: jest.fn(() => ({ lean: () => ({ exec: async () => asset }) })),
find: jest.fn(() => ({ sort: () => ({ lean: () => ({ exec: async () => [asset] }) }) })), deleteOne: jest.fn(() => ({ exec: async () => ({ deletedCount: 1 }) })) }; find: jest.fn(() => ({ sort: () => ({ lean: () => ({ exec: async () => [asset] }) }) })), deleteOne: jest.fn(() => ({ exec: async () => ({ deletedCount: 1 }) })) };
draw = { renderGraphic: jest.fn(() => rendered) }; draw = { renderGraphic: jest.fn(() => rendered) };
collection = { findOne: jest.fn<() => Promise<unknown>>().mockResolvedValue(null), updateMany: jest.fn(async () => ({ modifiedCount: 1 })) }; collection = { findOne: jest.fn<() => Promise<unknown>>().mockResolvedValue(null), updateMany: jest.fn(async () => ({ modifiedCount: 1 })) };
@@ -34,6 +34,47 @@ describe('Feste Grafikbibliothek', () => {
expect(Buffer.from(result.xamlBase64, 'base64').toString('utf8')).toBe(result.xaml); expect(Buffer.from(result.xamlBase64, 'base64').toString('utf8')).toBe(result.xaml);
expect(model.create.mock.calls[0][0].generator.ergebnis).toBeUndefined(); expect(model.create.mock.calls[0][0].generator.ergebnis).toBeUndefined();
}); });
it('benennt die Grafik und alle ID-basierten Verwendungen ohne neue Grafikgenerierung um', async () => {
const result = await service.rename(id, { anlageId: 'a1', version: 0, name: ' Endschalter_oben.xaml ' });
expect(result.name).toBe('Endschalter_oben');
expect(result.version).toBe(1);
expect(result.svg).toBe(asset.svg);
expect(result.xaml).toBe(asset.xaml);
expect(draw.renderGraphic).not.toHaveBeenCalled();
expect(model.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: id, anlageId: 'a1', $or: [{ revision: 0 }, { revision: { $exists: false } }] },
{ $set: { name: 'Endschalter_oben', nameKey: 'endschalter_oben' }, $inc: { revision: 1 } },
{ new: true, runValidators: true });
expect(collection.updateMany).toHaveBeenCalledTimes(4);
const calls = collection.updateMany.mock.calls as any[];
for (const [filter, update, options] of calls.slice(0, 3)) {
expect(filter).toEqual({ anlageId: 'a1', 'rows.graphics.libraryId': id });
expect(update.$set).toEqual({
'rows.$[].graphics.$[graphic].name': 'Endschalter_oben',
'rows.$[].graphics.$[graphic].generator.ergebnis.name': 'Endschalter_oben',
});
expect(options.arrayFilters).toEqual([{ 'graphic.libraryId': id }]);
expect(update.$inc).toEqual({ revision: 1 });
}
expect(calls[3][1].$set).toEqual({ 'elemente.$[element].varianten.$[variant].libraryName': 'Endschalter_oben' });
expect(calls[3][2].arrayFilters).toContainEqual({ 'variant.libraryId': id });
});
it('verteilt bei Namensduplikaten oder Versionskonflikten keine Änderungen', async () => {
model.findOneAndUpdate.mockReturnValueOnce({ lean: () => ({ exec: async () => { throw { code: 11000 }; } }) });
await expect(service.rename(id, { anlageId: 'a1', version: 0, name: 'Duplikat' })).rejects.toThrow('bereits vergeben');
model.findOneAndUpdate.mockReturnValueOnce({ lean: () => ({ exec: async () => null }) });
await expect(service.rename(id, { anlageId: 'a1', version: 0, name: 'Neuer_Name' })).rejects.toThrow('inzwischen');
expect(collection.updateMany).not.toHaveBeenCalled();
});
it('lehnt ungültige Namen, Versionen und fremde Anlagen vor dem Umbenennen ab', async () => {
await expect(service.rename(id, { anlageId: 'fremd', version: 0, name: 'Neu' })).rejects.toThrow('Anlage');
await expect(service.rename(id, { anlageId: 'a1', version: -1, name: 'Neu' })).rejects.toThrow('Version');
for (const name of ['', ' ', '../Pfad']) {
await expect(service.rename(id, { anlageId: 'a1', version: 0, name })).rejects.toThrow();
}
expect(model.findOneAndUpdate).not.toHaveBeenCalled();
expect(collection.updateMany).not.toHaveBeenCalled();
});
it('aktualisiert alle vier Verwendungsarten ohne Platzierung oder Zustand zu überschreiben', async () => { it('aktualisiert alle vier Verwendungsarten ohne Platzierung oder Zustand zu überschreiben', async () => {
const result = await service.update(id, { ...input, version: 0 }); const result = await service.update(id, { ...input, version: 0 });
expect(result.version).toBe(1); expect(result.name).toBe('Punkt_gruen'); expect(result.version).toBe(1); expect(result.name).toBe('Punkt_gruen');
+1 -1
View File
@@ -1,7 +1,7 @@
import type { DrawDataDto } from '../../_dto/draw.dto'; import type { DrawDataDto } from '../../_dto/draw.dto';
export interface GrafikGeneratorDaten { export interface GrafikGeneratorDaten {
grafikTyp: 'motor' | 'punkt' | 'rechteck' | 'bandOben' | 'warnung' | 'pfeil' | 'anlageDurmin' | 'fahrwagenOben'; grafikTyp: 'motor' | 'endschalter' | 'text' | 'punkt' | 'rechteck' | 'bandOben' | 'warnung' | 'pfeil' | 'anlageDurmin' | 'fahrwagenOben';
config: Record<string, unknown>; config: Record<string, unknown>;
options: Record<string, unknown>; options: Record<string, unknown>;
ergebnis?: DrawDataDto; ergebnis?: DrawDataDto;
+8
View File
@@ -0,0 +1,8 @@
{
"rootDir": "../src",
"testEnvironment": "node",
"testRegex": "(anlage-pdf\\.(service|controller)|units\\.service)\\.spec\\.ts$",
"moduleFileExtensions": ["js", "json", "ts"],
"moduleNameMapper": { "^src/(.*)$": "<rootDir>/$1" },
"transform": { "^.+\\.(t|j)s$": ["ts-jest", { "tsconfig": { "module": "commonjs", "moduleResolution": "node", "isolatedModules": false, "resolvePackageJsonExports": false, "types": ["node", "express", "multer", "jest"] } }] }
}