SPB Git

Repository Public

AlertsSettingsTab.swift 21.4 KB 345 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/Alerts/AlertsSettingsTab.swift10// Description      : The alert settings screen: per-type switches grouped as11//                    the catalogue groups them, quiet hours, hourly cap,12//                    thresholds, the webhook (URL, details, secret rotation13//                    shown once, signed test call) and the browsers subscribed14//                    to Web Push (listed, testable, removable — a native app15//                    cannot create one, and the screen says why).16// Module           : Features17// Repository       : https://git.spboucher.ai/sp-wallet-macos18// Created          : 2026-11-1819// Last Modified    : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SwiftUI94import SPWalletCore9596struct AlertsSettingsTab: View {97    let model: AppModel98    @State private var flow: AlertsSettingsFlow?99100    var body: some View {101        ScrollView {102            VStack(alignment: .leading, spacing: 16) {103                if let flow {104                    if let e = flow.error { Banner(.danger, e) }105                    if let n = flow.notice { Banner(.ok, n) }106                    if let v = flow.view {107                        AlertsChannelsCard(model: model, flow: flow, view: v)108                        AlertsRulesCard(model: model, flow: flow, view: v)109                        AlertsThresholdsCard(model: model, flow: flow)110                        AlertsWebhookCard(model: model, flow: flow, view: v)111                    } else if flow.loading { ProgressView().frame(maxWidth: .infinity).padding(40) }112                    else { Card { OpsUnavailable(what: "Réglages des alertes", reason: flow.error ?? "Le serveur n’a pas répondu.") { Task { await flow.load() } } } }113                    AlertsPushCard(model: model, flow: flow)114                } else { ProgressView() }115            }.padding(24).frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)116        }117        .task { if flow == nil { let f = AlertsSettingsFlow(model: model); flow = f; await f.load() } }118        .sheet(isPresented: Binding(get: { flow?.freshSecret != nil }, set: { if !$0 { flow?.forgetSecret() } })) {119            if let flow, let secret = flow.freshSecret { AlertsSecretSheet(secret: secret) { flow.forgetSecret() } }120        }121    }122}123124private struct AlertsChannelsCard: View {125    let model: AppModel126    @Bindable var flow: AlertsSettingsFlow127    let view: AlertSettingsView128129    var body: some View {130        Card("Diffusion par le serveur", trailing: AnyView(OpsAsOf(date: flow.loadedAt))) {131            Text("Ces réglages sont ceux du serveur : ils gouvernent ses notifications push web et son webhook. Les notifications macOS de cette app se règlent dans l’onglet Alertes ; une alerte existe toujours dans l’app, quels que soient ces réglages.").font(.callout).foregroundStyle(.secondary)132            Toggle("Montants, prix et motifs dans les notifications push (écran verrouillé)", isOn: Binding(get: { view.settings.showDetails }, set: { v in Task { await flow.setShowDetails(v) } }))133            HStack {134                Text("Plafond par heure (critiques exceptées)").frame(width: 290, alignment: .leading)135                TextField("20", text: $flow.capPerHour).frame(width: 70).textFieldStyle(.roundedBorder)136                Button("Enregistrer") { Task { await flow.saveCap() } }.disabled(flow.capProblem != nil || flow.capPerHour == String(view.settings.capPerHour))137                if let p = flow.capProblem { Text(p).font(.caption).foregroundStyle(Theme.negative) }138            }139            Divider()140            Toggle("Heures calmes (les critiques passent toujours)", isOn: Binding(get: { view.settings.quiet.enabled }, set: { v in Task { await flow.setQuietEnabled(v) } }))141            HStack {142                Text("De").foregroundStyle(.secondary); TextField("22:00", text: $flow.quietStart).frame(width: 64).textFieldStyle(.roundedBorder)143                Text("à").foregroundStyle(.secondary); TextField("07:00", text: $flow.quietEnd).frame(width: 64).textFieldStyle(.roundedBorder)144                Text("fuseau").foregroundStyle(.secondary); TextField("America/Toronto", text: $flow.quietTz).frame(width: 190).textFieldStyle(.roundedBorder)145                Button("Enregistrer") { Task { await flow.saveQuiet() } }146                    .disabled(flow.quietProblem != nil || (flow.quietStart == view.settings.quiet.start && flow.quietEnd == view.settings.quiet.end && flow.quietTz == view.settings.quiet.tz))147                if let p = flow.quietProblem { Text(p).font(.caption).foregroundStyle(Theme.negative) }148            }149            Text("Le début de la journée des écarts de résultat (onglet Supervision) suit ce fuseau.").font(.caption).foregroundStyle(.secondary)150        }.disabled(!model.canOperate || flow.saving)151    }152}153154private struct AlertsRulesCard: View {155    let model: AppModel156    let flow: AlertsSettingsFlow157    let view: AlertSettingsView158    @State private var expanded: Set<String> = []159160    var body: some View {161        Card("Types d’alertes", trailing: AnyView(Text("\(view.kinds.count) types sur le serveur").font(.caption).foregroundStyle(.secondary))) {162            Text("Un type désactivé n’est plus notifié par le serveur (push web, webhook). Les types marqués « fixe » ne peuvent pas être coupés.").font(.callout).foregroundStyle(.secondary)163            let groups = AlertGroup.allCases + Array(Set(view.kinds.map(\.group))).filter { !AlertGroup.allCases.contains($0) }.sorted { $0.rawValue < $1.rawValue }164            ForEach(groups, id: \.self) { g in165                let kinds = view.kinds.filter { $0.group == g }166                if !kinds.isEmpty {167                    let on = kinds.filter { !$0.fixed && view.settings.isOn($0.kind) == true }.count, switchable = kinds.filter { !$0.fixed }.count168                    DisclosureGroup(isExpanded: Binding(get: { expanded.contains(g.rawValue) }, set: { if $0 { expanded.insert(g.rawValue) } else { expanded.remove(g.rawValue) } })) {169                        VStack(alignment: .leading, spacing: 4) {170                            HStack {171                                Button("Tout activer") { Task { await flow.setGroup(g, on: true) } }.disabled(on == switchable)172                                Button("Tout désactiver") { Task { await flow.setGroup(g, on: false) } }.disabled(on == 0)173                            }.controlSize(.small).padding(.vertical, 2)174                            ForEach(kinds, id: \.kind) { k in AlertsRuleRow(flow: flow, info: k, isOn: view.settings.isOn(k.kind)) }175                        }.padding(.leading, 6)176                    } label: {177                        HStack { Text(AlertsText.group(g)).fontWeight(.medium); Spacer(); Text("\(on) / \(switchable) activés").font(.callout).foregroundStyle(.secondary).monospacedDigit() }178                    }179                }180            }181        }.disabled(!model.canOperate || flow.saving)182    }183}184185private struct AlertsRuleRow: View {186    let flow: AlertsSettingsFlow187    let info: AlertKindInfo188    let isOn: Bool?189190    var body: some View {191        let def = AlertCatalog.definition(info.kind)192        HStack(alignment: .firstTextBaseline, spacing: 10) {193            Image(systemName: AlertsText.symbol(info.severity)).foregroundStyle(AlertsText.color(info.severity)).font(.caption).help("Gravité par défaut : \(AlertsText.severity(info.severity))")194            VStack(alignment: .leading, spacing: 0) {195                Text(def?.title.first ?? info.kind.rawValue)196                Text(info.kind.rawValue + (def == nil ? " · type inconnu de cette version de l’app" : "")).font(.caption).foregroundStyle(.secondary)197            }198            Spacer()199            if info.fixed { Text("Fixe — toujours actif").font(.caption).foregroundStyle(.secondary) }200            else if let isOn { Toggle("", isOn: Binding(get: { isOn }, set: { v in Task { await flow.setRule(info.kind, on: v) } })).labelsHidden().toggleStyle(.switch).controlSize(.small) }201            else { Text("État non renvoyé").font(.caption).foregroundStyle(Theme.warning) }202        }.padding(.vertical, 2)203    }204}205206private struct AlertsThresholdsCard: View {207    let model: AppModel208    @Bindable var flow: AlertsSettingsFlow209210    var body: some View {211        Card("Seuils de déclenchement") {212            ForEach(AlertsSettingsFlow.thresholdSpecs) { spec in213                HStack(alignment: .firstTextBaseline) {214                    VStack(alignment: .leading, spacing: 0) { Text(spec.label); Text(spec.help).font(.caption).foregroundStyle(.secondary) }.frame(width: 470, alignment: .leading)215                    TextField("", text: Binding(get: { flow.thresholds[spec.key] ?? "" }, set: { flow.thresholds[spec.key] = $0 })).frame(width: 90).textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing)216                    Text(spec.unit).foregroundStyle(.secondary).frame(width: 56, alignment: .leading)217                    if let p = flow.thresholdProblem(spec) { Text(p).font(.caption).foregroundStyle(Theme.negative) }218                    Spacer()219                }220            }221            HStack { Spacer(); if flow.saving { ProgressView().controlSize(.small) }; Button("Enregistrer les seuils") { Task { await flow.saveThresholds() } }.disabled(!flow.thresholdsValid) }222        }.disabled(!model.canOperate || flow.saving)223    }224}225226private struct AlertsWebhookCard: View {227    let model: AppModel228    @Bindable var flow: AlertsSettingsFlow229    let view: AlertSettingsView230    @State private var confirmRotate = false231232    var body: some View {233        let w = view.settings.webhook234        Card("Webhook sortant") {235            Text("Le serveur appelle cette adresse à chaque alerte notifiée, en signant le corps avec un secret partagé. Activer le webhook envoie des informations du portefeuille à un service tiers : ne l’activez que vers un service que vous contrôlez.").font(.callout).foregroundStyle(.secondary)236            HStack {237                TextField("https://…", text: $flow.webhookURL).textFieldStyle(.roundedBorder).font(Theme.monoSmall)238                Button("Enregistrer l’adresse") { Task { await flow.saveWebhookURL() } }.disabled(flow.webhookURLProblem != nil || flow.webhookURL.trimmingCharacters(in: .whitespaces) == w.url)239            }240            if let p = flow.webhookURLProblem { Text(p).font(.caption).foregroundStyle(Theme.negative) }241            Field(label: "Secret partagé", value: view.webhook.secretSet ? "Défini sur le serveur (jamais relisible)" : "Aucun — à générer avant d’activer")242            HStack {243                Toggle("Webhook activé", isOn: Binding(get: { w.enabled }, set: { v in Task { await flow.setWebhookEnabled(v) } }))244                    .disabled(!w.enabled && (!view.webhook.secretSet || w.url.isEmpty))245                    .help(!view.webhook.secretSet || w.url.isEmpty ? "Le serveur exige une adresse https enregistrée et un secret généré." : "")246                Spacer()247                Toggle("Inclure montants, prix et motifs", isOn: Binding(get: { w.details }, set: { v in Task { await flow.setWebhookDetails(v) } }))248            }249            if let sample = view.webhookSample {250                DisclosureGroup("Exemple exact d’un appel avec ces réglages") {251                    Text(OpsJSON.pretty(sample)).font(Theme.monoSmall).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(8)252                        .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 6))253                }254            }255            HStack {256                Button(view.webhook.secretSet ? "Remplacer le secret…" : "Générer le secret…") { confirmRotate = true }.disabled(flow.webhookBusy)257                Button("Envoyer un appel de test") { Task { await flow.testWebhook() } }.disabled(flow.webhookBusy || !view.webhook.secretSet || w.url.isEmpty)258                if flow.webhookBusy { ProgressView().controlSize(.small) }259                Spacer()260            }261            if let t = flow.webhookTest {262                if t.ok { Banner(.ok, "Le destinataire a accepté l’appel de test signé (HTTP \(t.status)). Cela prouve que l’adresse répond, pas que la signature y est vérifiée.") }263                else { Banner(.danger, t.status == 0 ? "Aucune réponse du destinataire\(t.error.map { " : \($0)" } ?? "")." : "Le destinataire a refusé l’appel de test (HTTP \(t.status))\(t.error.map { " : \($0)" } ?? "").") }264            }265        }266        .disabled(!model.canOperate || flow.saving)267        .confirmationDialog(view.webhook.secretSet ? "Remplacer le secret du webhook ?" : "Générer le secret du webhook ?", isPresented: $confirmRotate) {268            Button(view.webhook.secretSet ? "Remplacer le secret" : "Générer le secret", role: view.webhook.secretSet ? .destructive : nil) { Task { await flow.rotateSecret() } }269            Button("Annuler", role: .cancel) {}270        } message: {271            Text(view.webhook.secretSet ? "L’ancien secret cesse d’être valable immédiatement : le destinataire refusera les appels tant qu’il n’aura pas reçu le nouveau. Le nouveau secret n’est affiché qu’une fois."272                 : "Le secret est généré par le serveur et n’est affiché qu’une seule fois. L’app ne le conserve pas.")273        }274    }275}276277private struct AlertsSecretSheet: View {278    let secret: String279    let done: () -> Void280    @State private var copied = false281282    var body: some View {283        VStack(alignment: .leading, spacing: 14) {284            Text("Secret du webhook").font(.title2.weight(.semibold))285            Banner(.warning, "Ce secret n’est affiché que cette fois. Copiez-le dans la configuration du destinataire : ni le serveur ni cette app ne pourront le remontrer. En fermant cette fenêtre, l’app l’oublie.")286            Text(secret).font(Theme.mono).textSelection(.enabled).padding(10).frame(maxWidth: .infinity, alignment: .leading)287                .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 6))288            HStack {289                Button(copied ? "Copié" : "Copier") { copyToPasteboard(secret); copied = true }290                Text("Le presse-papiers est lisible par les autres apps : collez puis videz-le.").font(.caption).foregroundStyle(.secondary)291                Spacer()292                Button("J’ai copié le secret — fermer") { done() }.buttonStyle(.borderedProminent)293            }294        }.padding(22).frame(width: 620).interactiveDismissDisabled()295    }296}297298private struct AlertsPushCard: View {299    let model: AppModel300    let flow: AlertsSettingsFlow301    @State private var toRemove: PushSubscription?302303    var body: some View {304        Card("Appareils abonnés au push web (navigateurs)", trailing: AnyView(Button { Task { await flow.loadSubscriptions() } } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.borderless))) {305            Banner(.info, "Le serveur ne parle que le Web Push des navigateurs (VAPID) : il n’a pas de route APNs et refuse toute adresse qui n’est pas un service push de navigateur. Cette app Mac ne peut donc pas s’abonner ; elle lit les alertes du serveur et lève elle-même des notifications macOS locales tant qu’elle est ouverte. Les abonnements ci-dessous ont été créés depuis l’app web ; ils sont listés ici en lecture seule et peuvent être retirés.")306            if let err = flow.subscriptionsError, flow.subscriptions == nil { OpsUnavailable(what: "Liste des appareils", reason: err) { Task { await flow.loadSubscriptions() } } }307            else if let subs = flow.subscriptions {308                if subs.isEmpty { Text("Aucun navigateur abonné.").foregroundStyle(.secondary) }309                ForEach(subs) { s in310                    HStack(alignment: .top, spacing: 12) {311                        Image(systemName: "globe").foregroundStyle(.secondary)312                        VStack(alignment: .leading, spacing: 1) {313                            Text(s.label.isEmpty ? "Sans nom" : s.label).fontWeight(.medium)314                            Text("\(s.service) · …\(s.endpointTail) · langue \(s.locale)").font(.caption).foregroundStyle(.secondary)315                            Text(s.ua).font(.caption).foregroundStyle(.secondary).lineLimit(1)316                            Text("Abonné le \(Fmt.date(s.createdAt)) · dernier envoi accepté : \(Fmt.date(s.lastOkAt))\(s.failures > 0 ? " · \(s.failures) échecs" : "")").font(.caption).foregroundStyle(.secondary)317                            if let e = s.lastError { Text("Dernière erreur : \(e)").font(.caption).foregroundStyle(Theme.negative) }318                            if let r = flow.pushTest?.results.first(where: { $0.id == s.id }) {319                                Text(r.ok ? "Test accepté par le service push (HTTP \(r.status)) — l’affichage dépend du navigateur." : "Test refusé (HTTP \(r.status))\(r.error.map { " : \($0)" } ?? "")\(r.removed ? " — abonnement retiré par le serveur" : "")")320                                    .font(.caption).foregroundStyle(r.ok ? Theme.positive : Theme.negative)321                            }322                        }323                        Spacer()324                        Button("Tester") { Task { await flow.testPush(s.id) } }.disabled(flow.pushBusy)325                        Button("Retirer…", role: .destructive) { toRemove = s }.disabled(flow.pushBusy)326                    }.padding(.vertical, 3)327                }328            } else { ProgressView().controlSize(.small) }329        }330        .disabled(!model.canOperate)331        .confirmationDialog("Retirer cet appareil ?", isPresented: Binding(get: { toRemove != nil }, set: { if !$0 { toRemove = nil } }), presenting: toRemove) { s in332            Button("Retirer l’abonnement", role: .destructive) { Task { await flow.removeSubscription(s.id) } }333            Button("Annuler", role: .cancel) {}334        } message: { s in Text("« \(s.label.isEmpty ? s.service : s.label) » ne recevra plus de notification push. Il faudra s’y réabonner depuis l’app web de ce navigateur.") }335    }336}337338enum OpsJSON {339    /// Server data kept as served, indented for reading. Never interpreted.340    static func pretty(_ v: JSONValue) -> String {341        let e = JSONEncoder(); e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]342        return (try? e.encode(v)).flatMap { String(data: $0, encoding: .utf8) } ?? v.displayText343    }344}345
Files main
Menu

Theme