Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Alerts/AlertsHomeView.swift10// Description : The alert centre: the server's alert rows with the11// catalogue's wording, severity (icon + word + colour),12// group and unread filters, read state, paging towards the13// past, a detail with every parameter and an in-app14// destination. Offline it shows the last synchronized page,15// dated, with every action disabled. iPad: list and detail16// side by side.17// Module : Features18// Repository : https://git.spboucher.ai/sp-wallet-ios19// 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 SwiftUI95import SPWalletCore9697/** The list's state and its server calls (kept out of the view so the paging / marking logic is testable). */98@MainActor @Observable99final class AlertListModel {100 var items: [WalletAlert] = []101 var counters: AlertUnread?102 var group: AlertGroup?103 var unreadOnly = false104 var loading = false105 var loadingMore = false106 var reachedEnd = false107 var error: Error?108 /** Set when what is shown is the offline snapshot. */109 var cachedAt: Date?110 var loadedOnce = false111 static let pageSize = 40112 static let cacheKey = "alerts-list"113114 var query: AlertListQuery { AlertListQuery(limit: Self.pageSize, group: group, unreadOnly: unreadOnly) }115 var isFiltered: Bool { group != nil || unreadOnly }116117 func load(api: AlertsAPI, cache: AppCache, online: Bool) async {118 guard !loading else { return }119 loading = true; defer { loading = false; loadedOnce = true }120 guard online else { await loadCached(cache); return }121 do {122 let page = try await api.list(query)123 items = page.items; counters = page.counters; reachedEnd = page.items.count < Self.pageSize; error = nil; cachedAt = nil124 if !isFiltered { await cache.save(page, key: Self.cacheKey) }125 } catch let e {126 error = e127 if items.isEmpty { await loadCached(cache) }128 }129 }130131 private func loadCached(_ cache: AppCache) async {132 guard let c = await cache.load(AlertPage.self, key: Self.cacheKey) else { return }133 // the snapshot is the unfiltered first page; the filters are applied locally to what was saved, nothing more134 items = c.value.items.filter { (group == nil || $0.group == group) && (!unreadOnly || !$0.isRead) }135 counters = nil; cachedAt = c.savedAt; reachedEnd = true136 }137138 func loadMore(api: AlertsAPI) async {139 guard !loadingMore, !reachedEnd, let before = items.last?.id else { return }140 loadingMore = true; defer { loadingMore = false }141 do {142 var q = query; q.before = before143 let page = try await api.list(q)144 let known = Set(items.map(\.id))145 items += page.items.filter { !known.contains($0.id) }146 counters = page.counters; reachedEnd = page.items.count < Self.pageSize147 } catch let e { error = e }148 }149150 /** Mark read on the server, then show the server's answer: the row is re-read, not assumed. */151 func markRead(_ ids: [Int64]?, api: AlertsAPI, cache: AppCache) async -> AlertUnread? {152 do {153 if let ids { counters = try await api.markRead(ids: ids) } else { counters = try await api.markAllRead() }154 let page = try await api.list(AlertListQuery(limit: min(max(items.count, Self.pageSize), 200), group: group, unreadOnly: unreadOnly))155 items = page.items; counters = page.counters; error = nil156 if !isFiltered { await cache.save(page, key: Self.cacheKey) }157 return page.counters158 } catch let e { error = e; return nil }159 }160}161162struct AlertsHomeView: View {163 @Environment(AppModel.self) private var model164 @Environment(\.horizontalSizeClass) private var sizeClass165 private var center: AlertCenter { model.alertCenter }166 @State private var list = AlertListModel()167 @State private var selection: WalletAlert?168 @State private var showSystem = false169 @State private var showSettings = false170171 private var api: AlertsAPI { AlertsAPI(model.env.client) }172173 var body: some View {174 Group {175 if sizeClass == .regular {176 HStack(spacing: 0) {177 listView(split: true).frame(width: 400)178 Divider()179 Group {180 if let a = selection { AlertDetailView(alert: a, openSystemState: { showSystem = true }).id(a.id) }181 else { EmptyState(icon: "bell", title: String(localized: "Choisis une alerte"), message: String(localized: "Son détail s’affiche ici.")).frame(maxHeight: .infinity) }182 }.frame(maxWidth: .infinity)183 }184 } else { listView(split: false) }185 }186 .spPage()187 .navigationTitle(AppSection.alerts.title)188 .navigationDestination(isPresented: $showSystem) { SystemStateView().wallet(model) }189 .navigationDestination(isPresented: $showSettings) { AlertSettingsScreen().wallet(model) }190 .toolbar {191 ToolbarItem(placement: .topBarTrailing) {192 Button { Task { await mark(nil) } } label: { Image(systemName: "checkmark.circle") }193 .disabled(!model.canOperate || (list.counters?.unread ?? 0) == 0)194 .accessibilityLabel(String(localized: "Tout marquer comme lu")).accessibilityIdentifier("alerts.markAll")195 }196 ToolbarItem(placement: .topBarTrailing) {197 Menu {198 Button { showSettings = true } label: { Label(String(localized: "Réglages des alertes"), systemImage: "slider.horizontal.3") }199 Button { showSystem = true } label: { Label(String(localized: "État du système"), systemImage: "waveform.path.ecg") }200 } label: { Image(systemName: "ellipsis.circle") }201 .accessibilityLabel(String(localized: "Plus")).accessibilityIdentifier("alerts.more")202 }203 }204 .task { await reload() }205 .onChange(of: model.alertCenter.revision) { _, _ in Task { await reload() } }206 .onChange(of: list.group) { _, _ in selection = nil; Task { await reload() } }207 .onChange(of: list.unreadOnly) { _, _ in selection = nil; Task { await reload() } }208 }209210 private func reload() async {211 await list.load(api: api, cache: model.env.cache, online: model.canOperate)212 if let s = selection, let fresh = list.items.first(where: { $0.id == s.id }), fresh != s { selection = fresh }213 }214215 private func mark(_ ids: [Int64]?) async {216 guard model.canOperate, let c = await list.markRead(ids, api: api, cache: model.env.cache) else { return }217 center.applyCounters(c, unreadRows: list.isFiltered ? nil : list.items.filter { !$0.isRead })218 if let s = selection, let fresh = list.items.first(where: { $0.id == s.id }), fresh != s { selection = fresh }219 }220221 @ViewBuilder private func listView(split: Bool) -> some View {222 let days = Dictionary(grouping: list.items) { Calendar.current.startOfDay(for: $0.ts) }.sorted { $0.key > $1.key }223 List {224 Section {225 FreshnessBanner().listRowInsets(.init()).listRowBackground(Color.clear)226 if let at = list.cachedAt {227 Notice(tone: .warn, title: String(localized: "Alertes du \(at.formatted(date: .abbreviated, time: .shortened))"),228 message: String(localized: "Dernière page synchronisée. Des alertes plus récentes peuvent exister sur le serveur."), icon: "clock")229 .listRowInsets(.init()).listRowBackground(Color.clear).accessibilityIdentifier("alerts.cached")230 }231 filters.listRowInsets(.init(top: 4, leading: 0, bottom: 4, trailing: 0)).listRowBackground(Color.clear).listRowSeparator(.hidden)232 HStack {233 if let c = list.counters {234 Text(c.unread == 0 ? String(localized: "Aucune alerte non lue") : String(localized: "\(c.unread) non lue(s)"))235 .accessibilityIdentifier("alerts.unread")236 if c.critical > 0 { Pill(text: String(localized: "\(c.critical) critique(s)"), tone: .danger, icon: AlertSeverity.critical.symbol) }237 } else if list.cachedAt != nil { Text(String(localized: "Compteur indisponible hors ligne")) }238 Spacer()239 }240 .font(.spFootnote).foregroundStyle(Theme.mute).listRowBackground(Color.clear).listRowSeparator(.hidden)241 }242 if let e = list.error { Section { ErrorNotice(error: e) { Task { await reload() } } } }243 if !list.loadedOnce { ProgressView().frame(maxWidth: .infinity).listRowBackground(Color.clear) }244 else if list.items.isEmpty, list.error == nil {245 EmptyState(icon: "bell.slash", title: list.isFiltered ? String(localized: "Aucune alerte pour ce filtre") : String(localized: "Aucune alerte"),246 message: list.isFiltered ? nil : String(localized: "Le serveur n’a enregistré aucune alerte."))247 .listRowBackground(Color.clear)248 }249 ForEach(days, id: \.key) { day, rows in250 Section(day.formatted(date: .complete, time: .omitted)) {251 ForEach(rows) { a in252 Group {253 if split {254 Button { selection = a } label: { AlertRow(alert: a) }.buttonStyle(.plain)255 .listRowBackground(selection?.id == a.id ? Theme.elev : Theme.surface)256 } else { NavigationLink { AlertDetailView(alert: a, openSystemState: nil).wallet(model) } label: { AlertRow(alert: a) } }257 }258 .accessibilityIdentifier("alerts.row")259 .swipeActions(edge: .trailing) {260 if !a.isRead { Button { Task { await mark([a.id]) } } label: { Label(String(localized: "Lue"), systemImage: "checkmark") }.tint(Theme.blue).disabled(!model.canOperate) }261 }262 }263 }264 }265 if !list.items.isEmpty, !list.reachedEnd {266 Button { Task { await list.loadMore(api: api) } } label: {267 HStack { Spacer(); if list.loadingMore { ProgressView() } else { Text(String(localized: "Afficher les alertes plus anciennes")) }; Spacer() }268 }269 .disabled(!model.canOperate).accessibilityIdentifier("alerts.more.older")270 }271 }272 .listStyle(.insetGrouped).scrollContentBackground(.hidden)273 .refreshable { await reload(); await center.poll(forceRows: true) }274 }275276 private var filters: some View {277 ScrollView(.horizontal, showsIndicators: false) {278 HStack(spacing: 8) {279 chip(String(localized: "Non lues"), on: list.unreadOnly, icon: "circle.fill", id: "alerts.filter.unread") { list.unreadOnly.toggle() }280 Divider().frame(height: 22)281 chip(String(localized: "Toutes"), on: list.group == nil, icon: nil, id: "alerts.filter.all") { list.group = nil }282 ForEach(AlertGroup.allCases, id: \.rawValue) { g in283 chip(g.label, on: list.group == g, icon: nil, id: "alerts.filter.\(g.rawValue)") { list.group = g }284 }285 }.padding(.horizontal, 2)286 }287 }288289 private func chip(_ title: String, on: Bool, icon: String?, id: String, action: @escaping () -> Void) -> some View {290 Button(action: action) {291 HStack(spacing: 5) {292 if on { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)) } else if let icon { Image(systemName: icon).font(.system(size: 7)) }293 Text(title).font(.system(size: 13.5, weight: .semibold))294 }295 .padding(.horizontal, 13).frame(minHeight: 36)296 .foregroundStyle(on ? Theme.onPrimary : Theme.ink)297 .background(on ? Theme.primary : Theme.surface, in: Capsule())298 .overlay(Capsule().strokeBorder(Theme.hairline, lineWidth: on ? 0 : 0.5))299 }300 .buttonStyle(.plain).accessibilityIdentifier(id).accessibilityAddTraits(on ? .isSelected : [])301 }302}303304struct SeverityPlate: View {305 let severity: AlertSeverity306 var size: CGFloat = 38307 var body: some View {308 Circle().fill(severity.tone.color.opacity(0.13)).frame(width: size, height: size)309 .overlay(Image(systemName: severity.symbol).font(.system(size: size * 0.42, weight: .semibold)).foregroundStyle(severity.tone.color))310 .accessibilityHidden(true)311 }312}313314struct AlertRow: View {315 @Environment(AppModel.self) private var model316 let alert: WalletAlert317 var body: some View {318 // with « masquer les soldes » the list uses the catalogue's wording without amounts319 let t = alert.text(locale: AlertPresentation.locale, detail: !model.hideBalances)320 HStack(alignment: .top, spacing: 12) {321 SeverityPlate(severity: alert.severity)322 VStack(alignment: .leading, spacing: 4) {323 HStack(alignment: .firstTextBaseline, spacing: 8) {324 Text(t.title).font(.system(size: 15.5, weight: alert.isRead ? .medium : .semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)325 Spacer(minLength: 4)326 Text(AlertPresentation.age(alert.ts)).font(.system(size: 12)).foregroundStyle(Theme.mute).lineLimit(1).layoutPriority(1)327 }328 if !t.body.isEmpty { Text(t.body).font(.spCallout).foregroundStyle(alert.isRead ? Theme.mute : Theme.ink.opacity(0.85)).fixedSize(horizontal: false, vertical: true) }329 HStack(spacing: 6) {330 Pill(text: alert.severity.word, tone: alert.severity.tone, icon: alert.severity.symbol)331 Pill(text: alert.group.label)332 if alert.count > 1 { Pill(text: "×\(alert.count)") }333 }.padding(.top, 2)334 }335 Circle().fill(alert.isRead ? Color.clear : Theme.blue).frame(width: 9, height: 9).padding(.top, 6).accessibilityHidden(true)336 }337 .padding(.vertical, 4).contentShape(Rectangle())338 .accessibilityElement(children: .combine)339 .accessibilityValue(alert.isRead ? String(localized: "lue") : String(localized: "non lue"))340 }341}342343struct AlertDetailView: View {344 @Environment(AppModel.self) private var model345 let alert: WalletAlert346 /** Split layout: the list's own stack opens the system state. Pushed detail (nil): it links to it itself. */347 var openSystemState: (() -> Void)?348349 var body: some View {350 let t = alert.text(locale: AlertPresentation.locale, detail: !model.hideBalances)351 let dest = AlertPresentation.destination(alert)352 ScrollView {353 VStack(alignment: .leading, spacing: Theme.Space.section) {354 VStack(alignment: .leading, spacing: 10) {355 HStack(spacing: 10) {356 SeverityPlate(severity: alert.severity, size: 44)357 VStack(alignment: .leading, spacing: 4) {358 Pill(text: alert.severity.word, tone: alert.severity.tone, icon: alert.severity.symbol)359 Text(alert.isRead ? String(localized: "Lue") : String(localized: "Non lue")).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("alert.readState")360 }361 }362 Text(t.title).font(.system(size: 24, weight: .semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("alert.title")363 if !t.body.isEmpty { Text(t.body).font(.spBody).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }364 if !alert.kind.isKnown {365 Notice(tone: .info, title: String(localized: "Type d’alerte inconnu de cette version"), message: String(localized: "Le serveur a émis un type que l’app ne sait pas formuler. Ses paramètres sont affichés tels quels ci-dessous."))366 }367 }368 switch dest {369 case .section(let s):370 Button { model.router.go(s) } label: { Label(String(localized: "Ouvrir : \(s.title)"), systemImage: s.icon) }.buttonStyle(.spSecondary).accessibilityIdentifier("alert.open")371 case .systemState:372 if let openSystemState {373 Button(action: openSystemState) { Label(String(localized: "Ouvrir : État du système"), systemImage: "waveform.path.ecg") }.buttonStyle(.spSecondary).accessibilityIdentifier("alert.open")374 } else {375 NavigationLink { SystemStateView().wallet(model) } label: { Label(String(localized: "Ouvrir : État du système"), systemImage: "waveform.path.ecg") }.buttonStyle(.spSecondary).accessibilityIdentifier("alert.open")376 }377 case .none: EmptyView()378 }379 VStack(alignment: .leading, spacing: 0) {380 FieldRow(label: String(localized: "Date de l’événement"), value: alert.ts.formatted(date: .complete, time: .standard)); Divider()381 FieldRow(label: String(localized: "Catégorie"), value: alert.group.label); Divider()382 FieldRow(label: String(localized: "Type (code du serveur)"), value: alert.kind.rawValue, mono: true); Divider()383 FieldRow(label: String(localized: "Occurrences regroupées"), value: String(alert.count))384 if let r = alert.readAt { Divider(); FieldRow(label: String(localized: "Lue le"), value: r.formatted(date: .abbreviated, time: .standard)) }385 Divider(); FieldRow(label: String(localized: "Canaux du serveur (push web, webhook)"), value: alert.delivery.label)386 if let p = alert.channels?.push { Divider(); FieldRow(label: String(localized: "Push web"), value: String(localized: "\(p.sent) envoyé(s), \(p.failed) échec(s)")) }387 if let w = alert.channels?.webhook { Divider(); FieldRow(label: "Webhook", value: w.ok ? String(localized: "accepté (HTTP \(w.status))") : String(localized: "échec (HTTP \(w.status))"), tone: w.ok ? nil : .danger) }388 }.spCard(padding: 16)389 if let s = alert.subject, s.type != "none" {390 VStack(alignment: .leading, spacing: 0) {391 SectionHeader(title: String(localized: "Objet")).padding(.bottom, 4)392 FieldRow(label: String(localized: "Nature"), value: s.type)393 if let id = s.id, !id.isEmpty { Divider(); FieldRow(label: String(localized: "Identifiant"), value: id, mono: true, copyable: true) }394 if let n = s.network, !n.isEmpty { Divider(); FieldRow(label: String(localized: "Réseau"), value: model.network(n)?.name ?? n) }395 }.spCard(padding: 16)396 }397 VStack(alignment: .leading, spacing: 0) {398 SectionHeader(title: String(localized: "Paramètres, tels que servis")).padding(.bottom, 4)399 let keys = alert.params.keys.sorted()400 ForEach(Array(keys.enumerated()), id: \.element) { i, k in401 if i > 0 { Divider() }402 let hidden = model.hideBalances && !AlertCatalog.safeParams.contains(k)403 FieldRow(label: k, value: hidden ? String(localized: "masqué (soldes masqués)") : Self.text(alert.params[k]), mono: !hidden, copyable: !hidden)404 }405 if keys.isEmpty { Text(String(localized: "Aucun paramètre.")).font(.spFootnote).foregroundStyle(Theme.mute) }406 }.spCard(padding: 16)407 }408 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 16)409 .frame(maxWidth: 760).frame(maxWidth: .infinity)410 }411 .spPage()412 .navigationTitle(String(localized: "Alerte")).navigationBarTitleDisplayMode(.inline)413 .task {414 // opening the detail is reading it (same as the web); the answer updates the bell415 guard !alert.isRead, model.canOperate, let c = try? await AlertsAPI(model.env.client).markRead(ids: [alert.id]) else { return }416 model.alertCenter.applyCounters(c)417 }418 }419420 static func text(_ v: JSONValue?) -> String {421 switch v {422 case .string(let s)?: s423 case .int(let i)?: String(i)424 case .double(let d)?: String(d)425 case .bool(let b)?: b ? "true" : "false"426 default: "—"427 }428 }429}430