SPB Git

Repository Public

AlertsListTab.swift 16.0 KB 258 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/AlertsListTab.swift10// Description      : The list of the server's alerts: severity, type (the11//                    catalogue's French title), time, read state and the12//                    alert's own sentence; filters by severity, catalogue13//                    group, subject and unread; read marks; the live state of14//                    the stream; and a detail pane with every fact the server15//                    attached to the alert.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 AlertsListTab: View {97    let model: AppModel98    @Bindable var center: AlertsCenter99    @State private var selection: Set<WalletAlert.ID> = []100    @State private var notifyLevel = AlertsNotifyLevel.stored101    @State private var notifyDetails = AlertsNotifyLevel.showDetails102    @State private var confirmAllRead = false103104    var body: some View {105        let rows = center.shown106        VStack(spacing: 0) {107            filters108            if let e = center.error { Banner(.danger, e).padding(.horizontal, 24).padding(.bottom, 8) }109            if center.fromCache, let d = center.loadedAt { Banner(.warning, "Liste lue le \(Fmt.date(d)) — elle n’a pas pu être rafraîchie. Des alertes plus récentes peuvent manquer.").padding(.horizontal, 24).padding(.bottom, 8) }110            Table(rows, selection: $selection) {111                TableColumn("") { a in Circle().fill(a.isRead ? Color.clear : Theme.accent).frame(width: 8, height: 8).accessibilityLabel(a.isRead ? "Lue" : "Non lue") }.width(14)112                TableColumn("Gravité") { a in Label(AlertsText.severity(a.severity), systemImage: AlertsText.symbol(a.severity)).foregroundStyle(AlertsText.color(a.severity)).font(.callout) }.width(min: 110, ideal: 130)113                TableColumn("Type") { a in Text(AlertsText.sentence(a).title).fontWeight(a.isRead ? .regular : .semibold).lineLimit(1) }.width(min: 170, ideal: 230)114                TableColumn("Fait rapporté") { a in115                    let body = AlertsText.sentence(a).body116                    Text(body.isEmpty ? "—" : body).lineLimit(1).foregroundStyle(a.isRead ? .secondary : .primary).help(body)117                }.width(min: 220, ideal: 420)118                TableColumn("Groupe") { a in Text(AlertsText.group(a.group)).foregroundStyle(.secondary) }.width(min: 80, ideal: 100)119                TableColumn("Date") { a in Text(Fmt.date(a.ts)).monospacedDigit().foregroundStyle(.secondary) }.width(min: 130, ideal: 150)120                TableColumn("×") { a in Text(a.count > 1 ? "\(a.count)" : "").monospacedDigit().help("Occurrences regroupées dans cette alerte") }.width(30)121            }122            .contextMenu(forSelectionType: WalletAlert.ID.self) { ids in123                Button("Marquer comme lue\(ids.count > 1 ? "s" : "")") { Task { await center.markRead(Array(ids)) } }.disabled(!model.canOperate || ids.isEmpty)124            }125            .overlay {126                if center.loading && rows.isEmpty { ProgressView() }127                else if rows.isEmpty {128                    EmptyState(symbol: "bell.slash", title: center.loadedAt == nil ? "Alertes non lues depuis le serveur" : "Aucune alerte ne correspond",129                               detail: center.theme != nil ? "Le filtre par sujet s’applique aux \(center.items.count) alertes déjà chargées. Chargez-en davantage ou retirez-le." : nil)130                }131            }132            footer(rows: rows)133            if selection.count == 1, let id = selection.first, let a = center.items.first(where: { $0.id == id }) {134                Divider()135                AlertsDetailPane(model: model, center: center, alert: a).frame(maxHeight: 290)136            }137        }138        .confirmationDialog("Marquer toutes les alertes comme lues ?", isPresented: $confirmAllRead) {139            Button("Tout marquer comme lu") { Task { await center.markAllRead() } }140            Button("Annuler", role: .cancel) {}141        } message: { Text("Cela concerne toutes les alertes du serveur, y compris celles qui ne sont pas affichées (\(center.counters?.unread ?? 0) non lues, dont \(center.counters?.critical ?? 0) critiques).") }142    }143144    private var filters: some View {145        VStack(alignment: .leading, spacing: 8) {146            HStack(spacing: 10) {147                Picker("Gravité", selection: $center.severity) {148                    Text("Toutes gravités").tag(AlertSeverity?.none)149                    ForEach([AlertSeverity.critical, .warning, .info], id: \.self) { Text(AlertsText.severity($0)).tag(AlertSeverity?.some($0)) }150                }.frame(width: 170)151                Picker("Groupe", selection: $center.group) {152                    Text("Tous groupes").tag(AlertGroup?.none)153                    ForEach(AlertGroup.allCases, id: \.self) { Text(AlertsText.group($0)).tag(AlertGroup?.some($0)) }154                }.frame(width: 150)155                Picker("Sujet", selection: $center.theme) {156                    Text("Tous sujets").tag(AlertsTheme?.none)157                    ForEach(AlertsTheme.allCases) { Text($0.label).tag(AlertsTheme?.some($0)) }158                }.frame(width: 210).help("Classement plus fin que les groupes du catalogue, appliqué aux alertes chargées. « Solde insuffisant » et « Frais élevés » n’ont pas de type propre sur le serveur : ils sont reconnus dans le motif d’un échec ou d’un refus.")159                Toggle("Non lues seulement", isOn: $center.unreadOnly).toggleStyle(.checkbox)160                Spacer()161                AlertsLiveBadge(state: center.live)162                Button { Task { await center.reload() } } label: { Image(systemName: "arrow.clockwise") }.help("Relire la liste").disabled(center.loading)163            }.labelsHidden()164            HStack(spacing: 10) {165                Text("Notifications macOS des nouvelles alertes :").font(.callout).foregroundStyle(.secondary)166                Picker("Seuil", selection: $notifyLevel) { ForEach(AlertsNotifyLevel.allCases) { Text($0.label).tag($0) } }.labelsHidden().frame(width: 250)167                    .onChange(of: notifyLevel) { AlertsNotifyLevel.stored = notifyLevel }168                Toggle("Montants et motifs dans le texte", isOn: $notifyDetails).toggleStyle(.checkbox)169                    .onChange(of: notifyDetails) { AlertsNotifyLevel.showDetails = notifyDetails }170                    .help("Désactivé : la notification ne contient que des noms, réseaux et compteurs (formulation « écran verrouillé » du serveur).")171                if !Notifier.enabled { Label("Notifications désactivées dans Réglages de l’app", systemImage: "bell.slash").font(.caption).foregroundStyle(Theme.warning) }172                Spacer()173            }174            if let t = center.theme, t.derivedFromReason {175                Text("« \(t.label) » n’est pas un type d’alerte du serveur : les lignes affichées sont des échecs ou refus dont le motif renvoyé par le serveur contient ces termes.").font(.caption).foregroundStyle(.secondary)176            }177        }.padding(.horizontal, 24).padding(.vertical, 10)178    }179180    private func footer(rows: [WalletAlert]) -> some View {181        HStack(spacing: 12) {182            Text("\(rows.count) affichées\(center.theme != nil ? " sur \(center.items.count) chargées" : "")").font(.callout).foregroundStyle(.secondary)183            if let d = center.loadedAt { ProvenanceTag(p: center.fromCache ? .stale : .verified, text: center.fromCache ? "Lue le \(Fmt.date(d))" : "Lue sur le serveur \(Fmt.relative(d))") }184            if !center.reachedEnd && !center.fromCache {185                Button(center.loadingMore ? "Chargement…" : "Charger des alertes plus anciennes") { Task { await center.loadMore() } }.disabled(center.loadingMore)186            } else if center.loadedAt != nil && !center.fromCache { Text("Fin de l’historique pour ces filtres.").font(.callout).foregroundStyle(.secondary) }187            Spacer()188            if center.marking { ProgressView().controlSize(.small) }189            Button("Marquer la sélection comme lue") { Task { await center.markRead(Array(selection)) } }190                .disabled(!model.canOperate || center.marking || !selection.contains { id in center.items.first { $0.id == id }?.isRead == false })191            Button("Tout marquer comme lu…") { confirmAllRead = true }.disabled(!model.canOperate || center.marking || (center.counters?.unread ?? 0) == 0)192        }.padding(.horizontal, 24).padding(.vertical, 8)193    }194}195196struct AlertsLiveBadge: View {197    let state: AlertsCenter.Live198    var body: some View {199        let (text, color, symbol): (String, Color, String) = {200            switch state {201            case .idle: ("Veille arrêtée", .secondary, "pause.circle")202            case .paused: ("En pause (app inactive, hors ligne ou session absente)", .secondary, "pause.circle")203            case .connecting: ("Connexion au flux…", Theme.warning, "dot.radiowaves.left.and.right")204            case .streaming(let since): ("En direct depuis \(since.formatted(date: .omitted, time: .shortened))", Theme.positive, "dot.radiowaves.left.and.right")205            case .reconnecting(let at, _): ("Reconnexion à \(at.formatted(date: .omitted, time: .standard))", Theme.warning, "arrow.triangle.2.circlepath")206            case .polling: ("Relevé des compteurs chaque minute", .secondary, "clock")207            }208        }()209        Label(text, systemImage: symbol).font(.caption).foregroundStyle(color)210            .help({ if case .reconnecting(_, let reason) = state { return reason }; return "Le flux en direct transporte les compteurs d’alertes ; la liste est relue à chaque changement." }())211    }212}213214struct AlertsDetailPane: View {215    let model: AppModel216    let center: AlertsCenter217    let alert: WalletAlert218219    var body: some View {220        let a = alert, t = AlertsText.sentence(a)221        ScrollView {222            VStack(alignment: .leading, spacing: 8) {223                HStack(spacing: 10) {224                    Image(systemName: AlertsText.symbol(a.severity)).foregroundStyle(AlertsText.color(a.severity)).font(.title2)225                    VStack(alignment: .leading, spacing: 1) {226                        Text(t.title).font(.headline)227                        Text("\(AlertsText.severity(a.severity)) · \(AlertsText.group(a.group)) · \(Fmt.dateSeconds(a.ts))").font(.caption).foregroundStyle(.secondary)228                    }229                    Spacer()230                    if a.isRead { Text("Lue le \(Fmt.date(a.readAt))").font(.caption).foregroundStyle(.secondary) }231                    else { Button("Marquer comme lue") { Task { await center.markRead([a.id]) } }.disabled(!model.canOperate || center.marking) }232                }233                if !t.body.isEmpty { Text(t.body).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }234                if AlertCatalog.definition(a.kind) == nil {235                    Banner(.info, "Ce type d’alerte n’est pas connu de cette version de l’app : il est affiché tel que le serveur l’a envoyé, sans interprétation.")236                }237                if let def = AlertCatalog.definition(a.kind), def.severity != a.severity {238                    Text("Gravité par défaut de ce type : \(AlertsText.severity(def.severity)). Cette alerte porte la sienne.").font(.caption).foregroundStyle(.secondary)239                }240                Divider()241                Text("Faits joints par le serveur").font(.caption).foregroundStyle(.secondary)242                ForEach(a.params.keys.sorted(), id: \.self) { k in243                    if let v = a.params[k] { Field(label: AlertsText.param(k), value: AlertsText.value(v), mono: ["to", "from", "ip", "clientId"].contains(k)) }244                }245                Field(label: "Code du type", value: a.kind.rawValue, mono: true)246                Field(label: "Identifiant", value: String(a.id), mono: true)247                if let s = a.subject, s.type != "none" { Field(label: "Concerne", value: AlertsText.subject(s), mono: s.id != nil) }248                Field(label: "Écran concerné", value: AlertsText.destination(a.path))249                let themes = AlertsTheme.of(a)250                if !themes.isEmpty { Field(label: "Sujets", value: AlertsTheme.allCases.filter(themes.contains).map(\.label).joined(separator: ", ")) }251                Field(label: "Notification serveur", value: AlertsText.delivery(a.delivery))252                if let p = a.channels?.push { Field(label: "Push web", value: "\(p.sent) remis au service, \(p.failed) en échec, \(p.removed) appareils retirés") }253                if let w = a.channels?.webhook { Field(label: "Webhook", value: w.ok ? "Accepté par le destinataire (HTTP \(w.status))" : (w.status == 0 ? "Aucune réponse du destinataire" : "Refusé par le destinataire (HTTP \(w.status))")) }254            }.padding(16)255        }256    }257}258
Files main
Menu

Theme