using System.Text.Json; using System.Text.Json.Nodes; using Gateway.Api.Domain; using Microsoft.Data.Sqlite; namespace Gateway.Api.Services; public sealed partial class GatewayStore { private const string PointSelect = """ SELECT id, display_name, protocol, scope, value_type, readable, writable, external_identity, address_json, created_at_utc, bacnet_object_kind, bacnet_object_instance FROM points """; private static GatewayPoint? FindActivePoint(SqliteConnection connection, SqliteTransaction? transaction, Guid id) { using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = PointSelect + " WHERE id = $id AND deleted_at_utc IS NULL;"; command.Parameters.AddWithValue("$id", id.ToString()); using var reader = command.ExecuteReader(); return reader.Read() ? ReadPoint(reader) : null; } private static bool MatchesPointDefinition(GatewayPoint current, GatewayPoint expected) => current.Protocol == expected.Protocol && current.Scope == expected.Scope && current.Readable == expected.Readable && current.Writable == expected.Writable && string.Equals(current.ValueType, expected.ValueType, StringComparison.OrdinalIgnoreCase) && current.ExternalIdentity == expected.ExternalIdentity && current.BacnetObjectKind == expected.BacnetObjectKind && current.BacnetObjectInstance == expected.BacnetObjectInstance && current.Address.GetRawText() == expected.Address.GetRawText(); public bool IsPointDefinitionCurrent(GatewayPoint expected) { using var connection = _database.OpenConnection(); return FindActivePoint(connection, null, expected.Id) is { } current && MatchesPointDefinition(current, expected); } private static GatewayPoint PreparePoint(SqliteConnection connection, SqliteTransaction transaction, CreatePointRequest request, GatewayPoint? existing) { ValidatePointRequest(request); var name = request.DisplayName.Trim(); var instance = request.BacnetObjectKind is null ? null : request.BacnetObjectInstance; if (request.Protocol == PointProtocol.Bacnet && request.Scope == PointScope.Gateway) { using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = """ SELECT EXISTS(SELECT 1 FROM points WHERE deleted_at_utc IS NULL AND protocol = 'Bacnet' AND scope = 'Gateway' AND display_name = $name AND id <> $id); """; command.Parameters.AddWithValue("$name", name); command.Parameters.AddWithValue("$id", existing?.Id.ToString() ?? ""); if ((long)command.ExecuteScalar()! != 0 || ReadGatewayConfiguration(connection, transaction).DeviceName == name) throw new DomainValidationException("BACnet-Object_Name muss innerhalb des Gateway-Geräts eindeutig sein."); var kind = request.BacnetObjectKind!.Value; instance ??= existing is { Protocol: PointProtocol.Bacnet, Scope: PointScope.Gateway } && existing.BacnetObjectKind == kind ? existing.BacnetObjectInstance : null; instance ??= GetNextBacnetObjectInstance(connection, transaction, kind); } return new GatewayPoint(existing?.Id ?? Guid.NewGuid(), name, request.Protocol, request.Scope, request.ValueType.Trim(), request.Readable, request.Writable, NormalizeNullable(request.ExternalIdentity), request.Address.Clone(), existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow, request.BacnetObjectKind, instance); } private static void BindPoint(SqliteCommand command, GatewayPoint point) { command.Parameters.AddWithValue("$id", point.Id.ToString()); command.Parameters.AddWithValue("$displayName", point.DisplayName); command.Parameters.AddWithValue("$protocol", point.Protocol.ToString()); command.Parameters.AddWithValue("$scope", point.Scope.ToString()); command.Parameters.AddWithValue("$valueType", point.ValueType); command.Parameters.AddWithValue("$readable", point.Readable ? 1 : 0); command.Parameters.AddWithValue("$writable", point.Writable ? 1 : 0); command.Parameters.AddWithValue("$externalIdentity", (object?)point.ExternalIdentity ?? DBNull.Value); command.Parameters.AddWithValue("$address", point.Address.GetRawText()); command.Parameters.AddWithValue("$bacnetObjectKind", (object?)point.BacnetObjectKind?.ToString() ?? DBNull.Value); command.Parameters.AddWithValue("$bacnetObjectInstance", (object?)point.BacnetObjectInstance ?? DBNull.Value); } private static DomainValidationException PointIdentityConflict(GatewayPoint point) => new(point.Scope == PointScope.Gateway && point.BacnetObjectKind is not null ? "BACnet-Objekttyp und -instanz sind bereits vergeben." : "Die externe Punktadresse existiert bereits."); public GatewayPoint? UpdatePoint(Guid id, CreatePointRequest request) { using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); var updated = UpdatePoint(connection, transaction, id, request); transaction.Commit(); return updated; } private static GatewayPoint? UpdatePoint(SqliteConnection connection, SqliteTransaction transaction, Guid id, CreatePointRequest request) { var current = FindActivePoint(connection, transaction, id); if (current is null) return null; var updated = PreparePoint(connection, transaction, request, current); bool signalChanged = current.Protocol != updated.Protocol || current.Scope != updated.Scope || !string.Equals(current.ValueType, updated.ValueType, StringComparison.OrdinalIgnoreCase) || current.ExternalIdentity != updated.ExternalIdentity || current.BacnetObjectKind != updated.BacnetObjectKind || current.BacnetObjectInstance != updated.BacnetObjectInstance || !JsonNode.DeepEquals(JsonNode.Parse(current.Address.GetRawText()), JsonNode.Parse(updated.Address.GetRawText())); var dependencies = ReadPointDependencies(connection, transaction, id); if ((signalChanged || current.Readable != updated.Readable || current.Writable != updated.Writable) && (dependencies.Mappings + dependencies.MqttMappings + dependencies.Alarms > 0)) throw new DomainValidationException("Der Punkt ist mit Mappings oder Alarmen verknüpft. Seine Adresse, sein Typ und seine Zugriffe sind in dieser Zuordnung fest. Der Name kann geändert werden."); if (!updated.Readable && current.Readable && dependencies.TrendLogs > 0) throw new DomainValidationException("Der Datenpunkt wird von einem Trendlog gelesen."); // Preserve identical address JSON so a formatting-only edit never recreates a native object. if (!signalChanged) updated = updated with { Address = current.Address }; using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = """ UPDATE points SET display_name=$displayName, protocol=$protocol, scope=$scope, value_type=$valueType, readable=$readable, writable=$writable, external_identity=$externalIdentity, address_json=$address, bacnet_object_kind=$bacnetObjectKind, bacnet_object_instance=$bacnetObjectInstance WHERE id=$id AND deleted_at_utc IS NULL; """; BindPoint(command, updated); try { command.ExecuteNonQuery(); } catch (SqliteException exception) when (exception.SqliteErrorCode == 19) { throw PointIdentityConflict(updated); } if (signalChanged) ClearPointRuntime(connection, transaction, id); else if (current.Writable && !updated.Writable) ExecutePointSql(connection, transaction, id, "DELETE FROM bacnet_commands WHERE point_id=$id AND state='pending';"); WriteAudit(connection, "point", $"Point '{updated.DisplayName}' updated ({id}).", transaction); return updated; } public PointDependencies? GetPointDependencies(Guid id) { using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(deferred: true); if (FindActivePoint(connection, transaction, id) is null) return null; return ReadPointDependencies(connection, transaction, id); } private static PointDependencies ReadPointDependencies(SqliteConnection connection, SqliteTransaction transaction, Guid id) { using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = """ SELECT (SELECT COUNT(*) FROM mappings WHERE source_point_id=$id OR target_point_id=$id), (SELECT COUNT(*) FROM mqtt_mappings WHERE point_id=$id), (SELECT COUNT(*) FROM alarm_rules WHERE point_id=$id), (SELECT COUNT(*) FROM trend_logs WHERE source_point_id=$id); """; command.Parameters.AddWithValue("$id", id.ToString()); using var reader = command.ExecuteReader(); reader.Read(); return new(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3)); } public bool DeletePoint(Guid id, string? confirmation) { using var connection = _database.OpenConnection(); using var transaction = connection.BeginTransaction(); var point = FindActivePoint(connection, transaction, id); if (point is null) return false; var dependencies = ReadPointDependencies(connection, transaction, id); if (!string.Equals(confirmation, dependencies.Confirmation, StringComparison.Ordinal) && (confirmation is not null || dependencies is not { Mappings: 0, MqttMappings: 0, Alarms: 0, TrendLogs: 0 })) throw new DomainValidationException("Der Punkt wird verwendet. Bitte prüfe die Verknüpfungen und bestätige das Löschen erneut."); ExecutePointSql(connection, transaction, id, """ DELETE FROM mappings WHERE source_point_id=$id OR target_point_id=$id; DELETE FROM mqtt_mappings WHERE point_id=$id; UPDATE notification_outbox SET state='Cancelled', result='Alarm point removed.' WHERE state='Pending' AND rule_id IN (SELECT id FROM alarm_rules WHERE point_id=$id); DELETE FROM alarm_rules WHERE point_id=$id; UPDATE trend_logs SET enabled=0 WHERE source_point_id=$id; UPDATE points SET deleted_at_utc=$now WHERE id=$id; """); ClearPointRuntime(connection, transaction, id); WriteAudit(connection, "point", $"Point '{point.DisplayName}' deleted ({id}).", transaction); transaction.Commit(); return true; } private static void ClearPointRuntime(SqliteConnection connection, SqliteTransaction transaction, Guid id) => ExecutePointSql(connection, transaction, id, """ DELETE FROM point_values WHERE point_id=$id; DELETE FROM bacnet_commands WHERE point_id=$id; DELETE FROM bacnet_properties WHERE point_id=$id; DELETE FROM bacnet_observations WHERE point_id=$id; """); private static void ExecutePointSql(SqliteConnection connection, SqliteTransaction transaction, Guid id, string sql) { using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = sql; command.Parameters.AddWithValue("$id", id.ToString()); command.Parameters.AddWithValue("$now", DateTimeOffset.UtcNow.ToString("O")); command.ExecuteNonQuery(); } }