Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/AlertsSettingsFlow.swift3// Description: The owner's alert settings as the server stores them: one switch per alert type, quiet hours, the hourly cap, thresholds, the outgoing webhook (secret generated by the server and shown once, never kept) and the browsers subscribed to Web Push. Every change is a partial update the server merges; the screen always shows the server's answer, not what was typed.4import Foundation5import SPWalletCore67@MainActor @Observable final class AlertsSettingsFlow {8 let model: AppModel9 private let api: AlertsAPI1011 private(set) var view: AlertSettingsView?12 private(set) var loadedAt: Date?13 private(set) var loading = false14 private(set) var saving = false15 var error: String?16 var notice: String?1718 // editable copies of the free-form fields (switches are sent at once)19 var quietStart = ""20 var quietEnd = ""21 var quietTz = ""22 var capPerHour = ""23 var thresholds: [String: String] = [:]24 var webhookURL = ""2526 // webhook27 /// The secret of the last rotation, in memory only until the owner closes the sheet. Never persisted, never logged.28 private(set) var freshSecret: String?29 private(set) var webhookTest: AlertWebhookTestResult?30 private(set) var webhookBusy = false3132 // push devices33 private(set) var subscriptions: [PushSubscription]?34 private(set) var subscriptionsError: String?35 private(set) var pushTest: PushTestResult?36 private(set) var pushBusy = false3738 init(model: AppModel) { self.model = model; api = AlertsAPI(model.client) }3940 struct ThresholdSpec: Identifiable {41 let key: String; let label: String; let unit: String; let range: ClosedRange<Double>; let integer: Bool; let help: String42 var id: String { key }43 }44 /// Bounds of services/api/src/alerts/store.ts (ThresholdsSchema): checked here to explain a refusal before the server gives it.45 static let thresholdSpecs: [ThresholdSpec] = [46 .init(key: "stuckMinutes", label: "Transfert ou échange non finalisé", unit: "min", range: 5...1440, integer: true, help: "Alerte « bloqué » quand une opération n’est toujours pas finale après ce délai."),47 .init(key: "bridgeStuckMinutes", label: "Pont non finalisé", unit: "min", range: 10...2880, integer: true, help: "Même règle pour un transfert inter-réseaux."),48 .init(key: "agentDigestMinutes", label: "Regroupement des ordres d’agent", unit: "min", range: 0...1440, integer: true, help: "Au plus une notification « ordre exécuté » par agent sur cette durée (0 = une par ordre)."),49 .init(key: "staleBars", label: "Données d’agent périmées", unit: "barres", range: 1...100, integer: true, help: "Nombre de barres manquantes avant l’alerte."),50 .init(key: "signalFailures", label: "Échecs de signal consécutifs", unit: "échecs", range: 1...50, integer: true, help: "Avant l’alerte d’échecs de signal d’un agent."),51 .init(key: "fundingUsd", label: "Paiement de financement", unit: "USD", range: 0...1_000_000, integer: false, help: "Montant absolu à partir duquel un paiement de financement est signalé."),52 .init(key: "diskFreePct", label: "Disque libre du serveur", unit: "%", range: 1...50, integer: false, help: "Alerte quand l’espace libre passe sous ce pourcentage."),53 .init(key: "backupHours", label: "Sauvegarde manquante", unit: "h", range: 1...720, integer: true, help: "Âge maximal de la dernière sauvegarde."),54 .init(key: "feedDebounceSec", label: "Connecteur en panne", unit: "s", range: 30...3600, integer: true, help: "Durée de panne avant l’alerte (un flux qui clignote ne dit rien)."),55 .init(key: "unknownOrderSec", label: "Ordre au sort inconnu", unit: "s", range: 15...3600, integer: true, help: "Délai avant de signaler un ordre dont la plateforme n’a pas confirmé le sort."),56 ]5758 func load() async {59 loading = true; defer { loading = false }60 do { adopt(try await api.settings()); error = nil } catch { self.error = model.describe(error) }61 await loadSubscriptions()62 }6364 private func adopt(_ v: AlertSettingsView) {65 view = v; loadedAt = Date()66 let s = v.settings67 quietStart = s.quiet.start; quietEnd = s.quiet.end; quietTz = s.quiet.tz68 capPerHour = String(s.capPerHour); webhookURL = s.webhook.url69 let t = s.thresholds70 thresholds = ["stuckMinutes": String(t.stuckMinutes), "bridgeStuckMinutes": String(t.bridgeStuckMinutes), "agentDigestMinutes": String(t.agentDigestMinutes), "staleBars": String(t.staleBars),71 "signalFailures": String(t.signalFailures), "fundingUsd": Self.plain(t.fundingUsd), "diskFreePct": Self.plain(t.diskFreePct), "backupHours": String(t.backupHours),72 "feedDebounceSec": String(t.feedDebounceSec), "unknownOrderSec": String(t.unknownOrderSec)]73 }74 private static func plain(_ d: Double) -> String { d == d.rounded() ? String(Int64(d)) : String(d) }75 private static func number(_ s: String) -> Double? { Double(s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")) }7677 private func send(_ patch: AlertSettingsPatch, done: String? = nil) async {78 guard model.canOperate, !saving else { return }79 saving = true; defer { saving = false }80 do { adopt(try await api.update(patch)); error = nil; notice = done } catch { self.error = model.describe(error) }81 }8283 // MARK: switches8485 func setRule(_ kind: AlertKind, on: Bool) async { await send(.rule(kind, on: on)) }86 func setGroup(_ group: AlertGroup, on: Bool) async {87 guard let v = view else { return }88 let rules = Dictionary(uniqueKeysWithValues: v.kinds.filter { $0.group == group && !$0.fixed }.map { ($0.kind.rawValue, on) })89 guard !rules.isEmpty else { return }90 await send(AlertSettingsPatch(rules: rules))91 }92 func setShowDetails(_ on: Bool) async { await send(AlertSettingsPatch(showDetails: on)) }93 func setQuietEnabled(_ on: Bool) async { await send(AlertSettingsPatch(quiet: .init(enabled: on))) }9495 // MARK: quiet hours, cap, thresholds9697 var quietProblem: String? {98 let hhmm = /^([01]\d|2[0-3]):[0-5]\d$/99 if quietStart.wholeMatch(of: hhmm) == nil || quietEnd.wholeMatch(of: hhmm) == nil { return "Heures au format HH:MM (24 h)." }100 if TimeZone(identifier: quietTz.trimmingCharacters(in: .whitespaces)) == nil { return "Fuseau horaire IANA inconnu (ex. America/Toronto)." }101 return nil102 }103 func saveQuiet() async {104 guard quietProblem == nil else { return }105 await send(AlertSettingsPatch(quiet: .init(start: quietStart, end: quietEnd, tz: quietTz.trimmingCharacters(in: .whitespaces))), done: "Heures calmes enregistrées.")106 }107108 var capProblem: String? { guard let n = Int(capPerHour.trimmingCharacters(in: .whitespaces)), (1...500).contains(n) else { return "Entre 1 et 500 par heure." }; return nil }109 func saveCap() async {110 guard capProblem == nil, let n = Int(capPerHour.trimmingCharacters(in: .whitespaces)) else { return }111 await send(AlertSettingsPatch(capPerHour: n), done: "Plafond horaire enregistré.")112 }113114 func thresholdProblem(_ spec: ThresholdSpec) -> String? {115 guard let v = Self.number(thresholds[spec.key] ?? ""), spec.range.contains(v), !spec.integer || v == v.rounded() else {116 return "\(spec.integer ? "Entier entre" : "Entre") \(Self.plain(spec.range.lowerBound)) et \(Self.plain(spec.range.upperBound)) \(spec.unit)"117 }118 return nil119 }120 var thresholdsValid: Bool { Self.thresholdSpecs.allSatisfy { thresholdProblem($0) == nil } }121 func saveThresholds() async {122 guard thresholdsValid else { return }123 func i(_ k: String) -> Int? { Self.number(thresholds[k] ?? "").map { Int($0) } }124 var t = AlertSettingsPatch.Thresholds()125 t.stuckMinutes = i("stuckMinutes"); t.bridgeStuckMinutes = i("bridgeStuckMinutes"); t.agentDigestMinutes = i("agentDigestMinutes"); t.staleBars = i("staleBars")126 t.signalFailures = i("signalFailures"); t.fundingUsd = Self.number(thresholds["fundingUsd"] ?? ""); t.diskFreePct = Self.number(thresholds["diskFreePct"] ?? "")127 t.backupHours = i("backupHours"); t.feedDebounceSec = i("feedDebounceSec"); t.unknownOrderSec = i("unknownOrderSec")128 await send(AlertSettingsPatch(thresholds: t), done: "Seuils enregistrés.")129 }130131 // MARK: webhook132133 var webhookURLProblem: String? {134 let s = webhookURL.trimmingCharacters(in: .whitespaces)135 if s.isEmpty { return nil }136 guard s.count <= 500, let u = URL(string: s), u.scheme == "https", u.host?.isEmpty == false else { return "L’adresse doit être une URL https (500 caractères au plus)." }137 return nil138 }139 func saveWebhookURL() async {140 guard webhookURLProblem == nil else { return }141 await send(AlertSettingsPatch(webhook: .init(url: webhookURL.trimmingCharacters(in: .whitespaces))), done: "Adresse du webhook enregistrée.")142 }143 func setWebhookEnabled(_ on: Bool) async { await send(AlertSettingsPatch(webhook: .init(enabled: on))) }144 func setWebhookDetails(_ on: Bool) async { await send(AlertSettingsPatch(webhook: .init(details: on))) }145146 func rotateSecret() async {147 guard model.canOperate, !webhookBusy else { return }148 webhookBusy = true; defer { webhookBusy = false }149 do {150 freshSecret = try await api.rotateWebhookSecret().secret151 if let v = try? await api.settings() { adopt(v) }152 error = nil153 } catch { self.error = model.describe(error) }154 }155 func forgetSecret() { freshSecret = nil }156157 func testWebhook() async {158 guard model.canOperate, !webhookBusy else { return }159 webhookBusy = true; webhookTest = nil; defer { webhookBusy = false }160 do { webhookTest = try await api.testWebhook(); error = nil } catch { self.error = model.describe(error) }161 }162163 // MARK: Web Push devices (browsers)164165 func loadSubscriptions() async {166 do { subscriptions = try await api.pushSubscriptions(); subscriptionsError = nil } catch { subscriptionsError = model.describe(error) }167 }168 func removeSubscription(_ id: String) async {169 guard model.canOperate, !pushBusy else { return }170 pushBusy = true; defer { pushBusy = false }171 do { try await api.deletePushSubscription(id: id); await loadSubscriptions(); notice = "Appareil retiré." } catch { self.error = model.describe(error) }172 }173 func testPush(_ id: String?) async {174 guard model.canOperate, !pushBusy else { return }175 pushBusy = true; pushTest = nil; defer { pushBusy = false }176 do { pushTest = try await api.testPush(id: id); await loadSubscriptions(); error = nil } catch { self.error = model.describe(error) }177 }178}179