SPB Git

Repository Public

AlertsView.swift 10.2 KB 218 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/AlertsView.swift10// Description      : Entry of the alerts and monitoring centre: the server's11//                    alerts (live), the alert settings, the read-only12//                    monitoring of capital / PnL / exposure / system health,13//                    and the unified timeline of operations. Read-only except14//                    for read marks and the owner's alert settings; nothing15//                    here moves funds.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 AlertsView: View {97    let model: AppModel98    enum Tab: String, CaseIterable, Identifiable {99        case alerts, settings, monitor, timeline100        var id: String { rawValue }101        var label: String { switch self { case .alerts: "Alertes"; case .settings: "Réglages"; case .monitor: "Supervision"; case .timeline: "Opérations" } }102    }103    @State private var tab: Tab = .alerts104    @State private var center: AlertsCenter?105106    var body: some View {107        VStack(spacing: 0) {108            HStack(alignment: .firstTextBaseline, spacing: 14) {109                Text("Alertes et supervision").font(.largeTitle.weight(.semibold))110                if let c = center?.counters, c.unread > 0 {111                    Text(c.critical > 0 ? "\(c.unread) non lues · \(c.critical) critiques" : "\(c.unread) non lues").font(.callout.weight(.medium))112                        .foregroundStyle(c.critical > 0 ? Theme.negative : Theme.warning)113                        .padding(.horizontal, 8).padding(.vertical, 3).background((c.critical > 0 ? Theme.negative : Theme.warning).opacity(0.13), in: Capsule())114                }115                Spacer()116                Picker("Section", selection: $tab) { ForEach(Tab.allCases) { Text($0.label).tag($0) } }.pickerStyle(.segmented).labelsHidden().frame(width: 440)117            }.padding([.horizontal, .top], 24).padding(.bottom, 10)118            if !model.canOperate { Banner(.warning, "Hors ligne ou session absente : les dernières données lues sont affichées avec leur date ; aucun réglage ne peut être modifié.").padding(.horizontal, 24).padding(.bottom, 8) }119            Divider()120            if let center {121                switch tab {122                case .alerts: AlertsListTab(model: model, center: center)123                case .settings: AlertsSettingsTab(model: model)124                case .monitor: OpsMonitorTab(model: model)125                case .timeline: OpsTimelineTab(model: model)126                }127            } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }128        }129        .background(Color(nsColor: .windowBackgroundColor))130        .task {131            let c = AlertsCenter.shared(model); center = c132            c.setVisible(true)133            await c.reload()134        }135        .onDisappear { center?.setVisible(false) }136    }137}138139/// A section header with the date its figures were read at — every monitoring block carries its own.140struct OpsAsOf: View {141    let date: Date?142    var prefix = "Lu"143    var body: some View {144        if let date { Text("\(prefix) \(Fmt.relative(date)) · \(Fmt.dateSeconds(date))").font(.caption).foregroundStyle(.secondary).monospacedDigit() }145    }146}147148/// The honest empty state of a section whose source failed: unavailable, with the reason — never a zero.149struct OpsUnavailable: View {150    let what: String151    let reason: String152    var retry: (() -> Void)?153    var body: some View {154        HStack(alignment: .top, spacing: 10) {155            ProvenanceTag(p: .unavailable)156            VStack(alignment: .leading, spacing: 2) {157                Text("\(what) : indisponible").fontWeight(.medium)158                Text(reason).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)159            }160            Spacer()161            if let retry { Button("Réessayer", action: retry) }162        }163    }164}165166/// Which money a figure is about. Real, test-network and simulated books never share a colour or a label.167enum OpsBookKind: Equatable {168    case real, testnet, paper, research, unknown(String)169    init(mode: String?) {170        switch mode?.lowercased() {171        case "live", "live-mainnet", "mainnet": self = .real172        case "live-testnet", "testnet": self = .testnet173        case "paper": self = .paper174        case "research": self = .research175        case let m?: self = .unknown(m)176        case nil: self = .unknown("")177        }178    }179    var label: String {180        switch self { case .real: "Réel"; case .testnet: "Testnet (fonds de test)"; case .paper: "Papier (simulé)"; case .research: "Recherche (backtest)"; case .unknown(let m): m.isEmpty ? "Mode non précisé" : m }181    }182    var color: Color { switch self { case .real: .orange; case .testnet: .purple; case .paper: .blue; case .research: .teal; case .unknown: .secondary } }183    var symbol: String { switch self { case .real: "banknote"; case .testnet: "hammer"; case .paper: "testtube.2"; case .research: "chart.xyaxis.line"; case .unknown: "questionmark.circle" } }184    var isSimulated: Bool { self == .paper || self == .research }185}186187struct OpsBookTag: View {188    let kind: OpsBookKind189    var body: some View {190        Label(kind.label, systemImage: kind.symbol).font(.caption.weight(.medium)).foregroundStyle(kind.color)191            .padding(.horizontal, 7).padding(.vertical, 3).background(kind.color.opacity(0.12), in: Capsule())192            .overlay(Capsule().strokeBorder(kind.color.opacity(kind.isSimulated ? 0.55 : 0), style: StrokeStyle(lineWidth: 1, dash: [3, 2])))193    }194}195196enum OpsFmt {197    /// A USD figure the server computed (an estimate in the server's rounding). nil is "—", never zero.198    static func usd(_ v: Double?) -> String { v.map { $0.formatted(.currency(code: "USD").precision(.fractionLength(2))) } ?? "—" }199    static func signedUsd(_ v: Double?) -> String {200        guard let v else { return "—" }201        return (v > 0 ? "+" : v < 0 ? "−" : "") + abs(v).formatted(.currency(code: "USD").precision(.fractionLength(2)))202    }203    static func number(_ v: Double?, digits: Int = 2) -> String { v.map { $0.formatted(.number.precision(.fractionLength(0...digits))) } ?? "—" }204    /// A fraction (0.0123) as a signed percentage.205    static func fraction(_ v: Double?, digits: Int = 2) -> String {206        guard let v else { return "—" }207        return (v > 0 ? "+" : v < 0 ? "−" : "") + abs(v * 100).formatted(.number.precision(.fractionLength(digits))) + " %"208    }209    static func age(seconds: Double?) -> String {210        guard let s = seconds else { return "—" }211        if s < 90 { return "\(Int(s)) s" }212        if s < 5400 { return "\(Int(s / 60)) min" }213        if s < 172_800 { return "\(Int(s / 3600)) h" }214        return "\(Int(s / 86_400)) j"215    }216    static func duration(ms: Double?) -> String { age(seconds: ms.map { $0 / 1000 }) }217}218
Files main
Menu

Theme