Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/Alerts/AlertsCenter.swift10// Description : The state of the alerts centre: the server's alert rows11// with their filters and paging, read marks, the live watch12// (the Core's SSE stream of unread counters while the screen13// is open, a slow poll of the same counters otherwise) and14// the macOS notifications of NEW alerts. Every alert shown15// or notified is a row the server returned; nothing is16// deduced locally.17// Module : Features18// Repository : https://git.spboucher.ai/sp-wallet-macos19// Created : 2026-11-1820// Last Modified : 2026-11-1821//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import AppKit95import Foundation96import SPWalletCore9798@MainActor @Observable final class AlertsCenter {99 enum Live: Equatable {100 case idle101 /// App in the background, offline or signed out: nothing is fetched.102 case paused103 case connecting104 case streaming(since: Date)105 case reconnecting(at: Date, reason: String)106 /// The screen is closed: only the unread counters are read, once a minute.107 case polling108 }109110 private static var current: AlertsCenter?111 /// One centre per app model: the watch and the notification memory survive the screen being closed and reopened.112 static func shared(_ model: AppModel) -> AlertsCenter {113 if let c = current, c.model === model { return c }114 let c = AlertsCenter(model: model); current = c; return c115 }116117 let model: AppModel118 private let api: AlertsAPI119 /// Alerts older than this are never notified (the app was not running when they happened).120 private let launchedAt = NSRunningApplication.current.launchDate ?? Date()121 private static let pageSize = 100, snapshotKey = "alerts.page"122123 // list124 private(set) var items: [WalletAlert] = []125 private(set) var counters: AlertUnread?126 private(set) var loadedAt: Date?127 private(set) var fromCache = false128 private(set) var loading = false129 private(set) var loadingMore = false130 private(set) var reachedEnd = false131 private(set) var marking = false132 var error: String?133134 // filters: severity, group and unread are the server's; the subject is applied to the rows already loaded135 var severity: AlertSeverity? { didSet { if severity != oldValue { Task { await reload() } } } }136 var group: AlertGroup? { didSet { if group != oldValue { Task { await reload() } } } }137 var unreadOnly = false { didSet { if unreadOnly != oldValue { Task { await reload() } } } }138 var theme: AlertsTheme?139140 // live141 private(set) var live: Live = .idle142 private var visible = false143 private var watchTask: Task<Void, Never>?144 private var highestSeen: Int64 = 0145 private var notified: Set<Int64> = []146 private var loadGeneration = 0147148 private init(model: AppModel) { self.model = model; api = AlertsAPI(model.client) }149150 var shown: [WalletAlert] { guard let t = theme else { return items }; return items.filter { AlertsTheme.of($0).contains(t) } }151 private var query: AlertListQuery { AlertListQuery(limit: Self.pageSize, severity: severity, group: group, unreadOnly: unreadOnly) }152 private var isUnfiltered: Bool { severity == nil && group == nil && !unreadOnly }153154 // MARK: - Reading155156 func reload() async {157 loadGeneration += 1; let generation = loadGeneration158 loading = true; defer { if generation == loadGeneration { loading = false } }159 do {160 let page = try await api.list(query)161 guard generation == loadGeneration else { return }162 items = page.items; counters = page.counters; reachedEnd = page.items.count < Self.pageSize163 loadedAt = Date(); fromCache = false; error = nil164 if isUnfiltered { await SnapshotStore.shared.save(page, as: Self.snapshotKey); noteNew(page.items) }165 } catch {166 guard generation == loadGeneration else { return }167 self.error = model.describe(error)168 if items.isEmpty, isUnfiltered, let snap: Snapshot<AlertPage> = await SnapshotStore.shared.load(Self.snapshotKey) {169 items = snap.value.items; counters = snap.value.counters; loadedAt = snap.savedAt; fromCache = true; reachedEnd = true170 } else if !items.isEmpty { fromCache = true }171 }172 }173174 func loadMore() async {175 guard !loadingMore, !reachedEnd, !fromCache, let last = items.last else { return }176 loadingMore = true; defer { loadingMore = false }177 let generation = loadGeneration178 var q = query; q.before = last.id179 do {180 let page = try await api.list(q)181 guard generation == loadGeneration else { return }182 let known = Set(items.map(\.id))183 items.append(contentsOf: page.items.filter { !known.contains($0.id) })184 counters = page.counters; reachedEnd = page.items.count < Self.pageSize; error = nil185 } catch { self.error = model.describe(error) }186 }187188 // MARK: - Read marks189190 func markRead(_ ids: [Int64]) async {191 let unread = ids.filter { id in items.first { $0.id == id }?.isRead == false }192 guard !unread.isEmpty, model.canOperate, !marking else { return }193 marking = true; defer { marking = false }194 do {195 var start = 0196 while start < unread.count { // the server takes at most 500 ids per call197 let end = min(start + 500, unread.count)198 counters = try await api.markRead(ids: Array(unread[start..<end])); start = end199 }200 await reload() // the read dates shown are the server's201 } catch { self.error = model.describe(error) }202 }203204 func markAllRead() async {205 guard model.canOperate, !marking else { return }206 marking = true; defer { marking = false }207 do { counters = try await api.markAllRead(); await reload() } catch { self.error = model.describe(error) }208 }209210 // MARK: - Live watch211212 /// Called when the alerts screen appears / disappears. The stream only runs while it is on screen.213 func setVisible(_ v: Bool) {214 visible = v215 if v { start() }216 }217218 /// Starts the watch if it is not running. Safe to call from the app shell at sign-in so that notifications do not wait for the screen to be opened once.219 func start() {220 guard watchTask == nil else { return }221 watchTask = Task { [weak self] in222 var backoff = OpsBackoff()223 while !Task.isCancelled {224 guard let self else { return }225 guard AppActivity.isActive, self.model.canOperate else {226 self.live = .paused227 try? await Task.sleep(for: .seconds(3)); continue228 }229 if self.visible {230 let outcome = await self.runStream()231 if Task.isCancelled { return }232 guard self.visible, AppActivity.isActive, self.model.canOperate else { continue }233 if outcome.delivered { backoff.reset() }234 let wait = outcome.delivered && outcome.reason == nil ? Duration.seconds(1) : backoff.next() // a stream the server ended on schedule is reopened at once235 self.live = .reconnecting(at: Date().addingTimeInterval(Double(wait.components.seconds)), reason: outcome.reason ?? "Flux terminé par le serveur (durée maximale de dix minutes).")236 try? await Task.sleep(for: wait)237 } else {238 self.live = .polling239 if let u = try? await self.api.unread() { await self.received(u) }240 for _ in 0..<30 { // one minute, leaving early when the screen opens241 if Task.isCancelled || self.visible { break }242 try? await Task.sleep(for: .seconds(2))243 }244 }245 }246 }247 }248249 func stop() { watchTask?.cancel(); watchTask = nil; live = .idle }250251 private struct StreamOutcome { var delivered = false; var reason: String? }252253 /// One connection of the SSE stream; returns when it ends, fails, or the screen / the app stops deserving it.254 private func runStream() async -> StreamOutcome {255 guard let request = await api.streamRequest() else { return StreamOutcome(reason: "Session absente.") }256 live = .connecting257 // the stream is dropped as soon as the screen closes, the app goes to the background, or the session is lost258 let keep: @MainActor @Sendable () -> Bool = { [weak self] in259 guard let self else { return false }260 return self.visible && AppActivity.isActive && self.model.canOperate261 }262 var out = StreamOutcome()263 do {264 for try await event in OpsEventStream.events(request, while: keep) {265 if !out.delivered { out.delivered = true; live = .streaming(since: Date()) }266 if case .unread(let u)? = AlertStreamEvent(event) { await received(u) }267 }268 } catch { out.reason = model.describe(error) }269 return out270 }271272 /// New counters from the stream or the poll: refresh what is on screen and look for alerts to notify.273 private func received(_ u: AlertUnread) async {274 let changed = counters != u275 counters = u276 if u.lastId > highestSeen { await fetchNew() }277 if changed, visible { await reload() }278 }279280 /// The newest rows, unfiltered, only to find the ones that appeared since the last look.281 private func fetchNew() async {282 guard let page = try? await api.list(AlertListQuery(limit: 50)) else { return }283 noteNew(page.items)284 }285286 // MARK: - Notifications287288 /// Raises one macOS notification per alert that is new, unread, created after the app's launch and at or above the owner's289 /// threshold. The text is the alert's own sentence from the catalogue (the backend's template) — never a paraphrase.290 private func noteNew(_ rows: [WalletAlert]) {291 let fresh = rows.filter { $0.id > highestSeen }292 highestSeen = max(highestSeen, rows.map(\.id).max() ?? 0)293 let level = AlertsNotifyLevel.stored294 let candidates = fresh.filter { !$0.isRead && $0.ts >= launchedAt && !notified.contains($0.id) && level.allows($0.severity) }.sorted { $0.id < $1.id }295 guard !candidates.isEmpty, Notifier.enabled else { candidates.forEach { notified.insert($0.id) }; return }296 // a burst is summarised rather than stacking dozens of banners; criticals always get their own297 let individually = candidates.filter { $0.severity >= .critical } + candidates.filter { $0.severity < .critical }.suffix(3)298 let shownIds = Set(individually.map(\.id))299 for a in candidates where shownIds.contains(a.id) {300 let t = AlertsText.sentence(a, detail: AlertsNotifyLevel.showDetails)301 let prefix = a.severity >= .critical ? "Critique — " : ""302 Notifier.post(title: prefix + t.title, body: t.body.isEmpty ? AlertsText.group(a.group) : t.body, id: "alert-\(a.id)")303 }304 let rest = candidates.count - shownIds.count305 if rest > 0 { Notifier.post(title: "\(rest) autres alertes", body: "Ouvrez le centre d’alertes de SP Wallet pour les lire.", id: "alert-burst-\(highestSeen)") }306 candidates.forEach { notified.insert($0.id) }307 }308}309