Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/OpsTimelineTab.swift3// Description: The unified timeline of operations (wallet, plans, orders, agent decisions, audit) as the server assembles it: filters by kind, mode, venue or network and period; pages walked with the server's cursor; the server's own CSV saved through NSSavePanel. Every row carries the money it is about — simulated rows are visibly marked — and the screen says when a source is missing or the history is bounded.4import SwiftUI5import UniformTypeIdentifiers6import SPWalletCore78@MainActor @Observable final class OpsTimelineModel {9 enum Period: String, CaseIterable, Identifiable {10 case day, week, month, all, custom11 var id: String { rawValue }12 var label: String { switch self { case .day: "24 heures"; case .week: "7 jours"; case .month: "30 jours"; case .all: "Tout l’historique"; case .custom: "Dates choisies" } }13 }1415 let model: AppModel16 private let api: DashboardAPI1718 var kind = "" { didSet { changed(oldValue != kind) } }19 var mode = "" { didSet { changed(oldValue != mode) } }20 var venue = "" { didSet { changed(oldValue != venue) } }21 var principal = "" { didSet { changed(oldValue != principal) } }22 var period: Period = .week { didSet { changed(oldValue != period) } }23 var from = Calendar.current.date(byAdding: .day, value: -7, to: Date()) ?? Date() { didSet { if period == .custom { changed(oldValue != from) } } }24 var to = Date() { didSet { if period == .custom { changed(oldValue != to) } } }2526 private(set) var items: [TimelineItem] = []27 private(set) var nextCursor: String?28 private(set) var loadedAt: Date?29 private(set) var serverTs: Date?30 private(set) var sourceErrors: [TimelinePage.SourceError] = []31 private(set) var audit: TimelinePage.Audit?32 private(set) var bounds: TimelinePage.Bounds?33 private(set) var kinds: [String] = []34 private(set) var knownVenues: [String] = []35 private(set) var loading = false36 private(set) var loadingMore = false37 private(set) var exporting = false38 var error: String?39 var exportMessage: String?40 private var generation = 04142 init(model: AppModel) { self.model = model; api = DashboardAPI(model.client) }4344 private func changed(_ really: Bool) { if really { Task { await reload() } } }4546 /// The filter as sent to the server. A relative period is anchored when the first page is read, so every page of one walk uses the same window.47 private var anchoredQuery = TimelineQuery()48 private func makeQuery() -> TimelineQuery {49 let now = Date()50 let window: (Date?, Date?) = switch period {51 case .day: (now.addingTimeInterval(-86_400), nil)52 case .week: (now.addingTimeInterval(-7 * 86_400), nil)53 case .month: (now.addingTimeInterval(-30 * 86_400), nil)54 case .all: (nil, nil)55 case .custom: (Calendar.current.startOfDay(for: min(from, to)), Calendar.current.date(byAdding: .day, value: 1, to: Calendar.current.startOfDay(for: max(from, to))))56 }57 func opt(_ s: String) -> String? { let t = s.trimmingCharacters(in: .whitespaces); return t.isEmpty ? nil : t }58 return TimelineQuery(kind: opt(kind), mode: opt(mode), venue: opt(venue), principal: opt(principal), from: window.0, to: window.1)59 }6061 func reload() async {62 generation += 1; let g = generation63 loading = true; defer { if g == generation { loading = false } }64 let q = makeQuery()65 do {66 let page = try await api.activity(q, limit: 100)67 guard g == generation else { return }68 anchoredQuery = q69 items = page.items; nextCursor = page.nextCursor; sourceErrors = page.errors; audit = page.audit; bounds = page.bounds70 if let k = page.kinds, !k.isEmpty { kinds = k }71 serverTs = page.ts; loadedAt = Date(); error = nil72 noteVenues(page.items)73 } catch { guard g == generation else { return }; self.error = model.describe(error) }74 }7576 func loadMore() async {77 guard let cursor = nextCursor, !loadingMore, !loading else { return }78 loadingMore = true; defer { loadingMore = false }79 let g = generation80 do {81 let page = try await api.activity(anchoredQuery, limit: 100, cursor: cursor)82 guard g == generation else { return }83 let known = Set(items.map(\.id))84 items.append(contentsOf: page.items.filter { !known.contains($0.id) })85 nextCursor = page.nextCursor; error = nil86 // a source that fails on a later page makes the whole walk incomplete87 for e in page.errors where !sourceErrors.contains(e) { sourceErrors.append(e) }88 noteVenues(page.items)89 } catch { self.error = model.describe(error) }90 }9192 private func noteVenues(_ rows: [TimelineItem]) {93 let seen = Set(knownVenues).union(rows.flatMap { [$0.venue, $0.network].compactMap { $0 } })94 knownVenues = seen.sorted()95 }9697 /// The server's own CSV of the filtered timeline (its quoting, its bound of 2 500 rows).98 func exportCSV() async {99 guard !exporting else { return }100 exporting = true; exportMessage = nil; defer { exporting = false }101 let q = makeQuery()102 do {103 let data = try await api.activityCSV(q)104 let panel = NSSavePanel()105 panel.allowedContentTypes = [.commaSeparatedText]; panel.canCreateDirectories = true106 panel.nameFieldStringValue = "sp-wallet-operations-\(Date().formatted(.iso8601.year().month().day())).csv"107 guard panel.runModal() == .OK, let url = panel.url else { return }108 do {109 try data.write(to: url, options: .atomic)110 let lines = data.reduce(into: 0) { if $1 == 0x0a { $0 += 1 } }111 exportMessage = "Exporté : \(url.lastPathComponent) (\(max(lines - 1, 0)) lignes ; le serveur en exporte 2 500 au plus). Les lignes simulées y portent leur mode."112 } catch { exportMessage = "Écriture impossible : \(error.localizedDescription)" }113 } catch { self.error = model.describe(error) }114 }115}116117enum OpsTimelineText {118 static func kind(_ k: String) -> String {119 switch k {120 case "transfer": "Envoi"; case "receive": "Réception"; case "swap": "Échange"; case "bridge": "Pont"; case "plan": "Plan"; case "order": "Ordre"121 case "agent": "Agent"; case "mandate": "Mandat"; case "risk": "Risque"; case "key": "Clé d’API"; case "security": "Sécurité"; default: k122 }123 }124 static func source(_ s: String) -> String {125 switch s { case "wallet": "Portefeuille"; case "plans": "Plans"; case "orders": "Ordres"; case "decisions": "Décisions d’agents"; case "audit": "Journal d’audit"; default: s }126 }127 static func principal(_ p: TimelineItem.Principal?) -> String {128 guard let p else { return "—" }129 switch p.kind {130 case "owner": return "Propriétaire"; case "agent": return "Agent \(p.id)"; case "api_key": return "Clé d’API \(p.id)"; case "system": return "Système"131 default: return "\(p.kind) \(p.id)"132 }133 }134 /// The status exactly as served, translated only for the wallet's own proposal states (broadcast is never shown as done).135 static func status(_ item: TimelineItem) -> String {136 guard let s = item.status else { return "—" }137 return item.source == "wallet" ? ErrorText.activityState(s) : s138 }139 static func quantity(_ q: TimelineItem.Quantity?) -> String? { q.map { "\(Fmt.amount($0.value, maxFraction: 8))\($0.symbol.map { " \($0)" } ?? "")" } }140}141142struct OpsTimelineTab: View {143 let model: AppModel144 @State private var data: OpsTimelineModel?145 @State private var selection: TimelineItem.ID?146147 var body: some View {148 VStack(spacing: 0) {149 if let data {150 OpsTimelineFilters(model: model, data: data)151 OpsTimelineNotices(data: data).padding(.horizontal, 24)152 Table(data.items, selection: $selection) {153 TableColumn("Date") { i in Text(Fmt.dateSeconds(i.at)).monospacedDigit() }.width(min: 150, ideal: 165)154 TableColumn("Argent concerné") { i in OpsBookTag(kind: OpsBookKind(mode: i.mode)) }.width(min: 150, ideal: 180)155 TableColumn("Type") { i in Text(OpsTimelineText.kind(i.kind)) }.width(min: 70, ideal: 90)156 TableColumn("Code") { i in Text(i.code).font(Theme.monoSmall).lineLimit(1) }.width(min: 110, ideal: 160)157 TableColumn("Objet") { i in158 Text([i.instrument, i.side, OpsTimelineText.quantity(i.amount), OpsTimelineText.quantity(i.received).map { "→ \($0)" }].compactMap { $0 }.joined(separator: " · ").opsIfEmpty("—")).monospacedDigit().lineLimit(1)159 }.width(min: 180, ideal: 280)160 TableColumn("Lieu") { i in Text([i.venue, i.network].compactMap { $0 }.joined(separator: " · ").opsIfEmpty("—")).lineLimit(1) }.width(min: 90, ideal: 130)161 TableColumn("État servi") { i in Text(OpsTimelineText.status(i)).lineLimit(1) }.width(min: 110, ideal: 170)162 TableColumn("Auteur") { i in Text(OpsTimelineText.principal(i.principal)).lineLimit(1).foregroundStyle(.secondary) }.width(min: 90, ideal: 130)163 }164 .overlay {165 if data.loading && data.items.isEmpty { ProgressView() }166 else if data.items.isEmpty { EmptyState(symbol: "clock.arrow.circlepath", title: data.loadedAt == nil ? "Historique non lu" : "Aucune opération pour ces filtres", detail: data.error) }167 }168 HStack(spacing: 12) {169 Text("\(data.items.count) opérations chargées").font(.callout).foregroundStyle(.secondary)170 if data.nextCursor != nil { Button(data.loadingMore ? "Chargement…" : "Charger la page suivante") { Task { await data.loadMore() } }.disabled(data.loadingMore || data.loading) }171 else if data.loadedAt != nil { Text("Fin de l’historique pour ces filtres.").font(.callout).foregroundStyle(.secondary) }172 Spacer()173 if let m = data.exportMessage { Text(m).font(.caption).foregroundStyle(.secondary).lineLimit(2) }174 OpsAsOf(date: data.serverTs ?? data.loadedAt, prefix: data.serverTs == nil ? "Reçu" : "Données du serveur")175 }.padding(.horizontal, 24).padding(.vertical, 8)176 if let id = selection, let item = data.items.first(where: { $0.id == id }) { Divider(); OpsTimelineDetail(item: item).frame(maxHeight: 260) }177 } else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }178 }179 .task { if data == nil { let d = OpsTimelineModel(model: model); data = d; await d.reload() } }180 }181}182183private struct OpsTimelineFilters: View {184 let model: AppModel185 @Bindable var data: OpsTimelineModel186187 var body: some View {188 VStack(alignment: .leading, spacing: 8) {189 HStack(spacing: 10) {190 Picker("Type", selection: $data.kind) { Text("Tous types").tag(""); ForEach(data.kinds, id: \.self) { Text(OpsTimelineText.kind($0)).tag($0) } }.frame(width: 150)191 Picker("Mode", selection: $data.mode) {192 Text("Tous modes").tag(""); Text("Réel").tag("live"); Text("Papier (simulé)").tag("paper"); Text("Recherche (backtest)").tag("research")193 }.frame(width: 190)194 Picker("Lieu", selection: $data.venue) {195 Text("Toutes plateformes et réseaux").tag("")196 ForEach(data.knownVenues, id: \.self) { Text(model.network($0)?.name ?? $0).tag($0) }197 if !data.venue.isEmpty, !data.knownVenues.contains(data.venue) { Text(data.venue).tag(data.venue) }198 }.frame(width: 230).help("Plateformes et réseaux rencontrés dans les pages déjà lues.")199 Picker("Auteur", selection: $data.principal) {200 Text("Tous auteurs").tag(""); Text("Propriétaire").tag("owner"); Text("Agents").tag("agent"); Text("Clés d’API").tag("api_key"); Text("Système").tag("system")201 }.frame(width: 150)202 Picker("Période", selection: $data.period) { ForEach(OpsTimelineModel.Period.allCases) { Text($0.label).tag($0) } }.frame(width: 170)203 Spacer()204 if data.exporting { ProgressView().controlSize(.small) }205 Button("Exporter en CSV…") { Task { await data.exportCSV() } }.disabled(data.exporting || model.isOffline).help("Le CSV est produit par le serveur avec les filtres affichés.")206 Button { Task { await data.reload() } } label: { Image(systemName: "arrow.clockwise") }.disabled(data.loading)207 }.labelsHidden()208 if data.period == .custom {209 HStack {210 DatePicker("Du", selection: $data.from, displayedComponents: .date).frame(width: 180)211 DatePicker("au", selection: $data.to, displayedComponents: .date).frame(width: 180)212 Text("(jours entiers, heure locale)").font(.caption).foregroundStyle(.secondary)213 }214 }215 }.padding(.horizontal, 24).padding(.vertical, 10)216 }217}218219private struct OpsTimelineNotices: View {220 let data: OpsTimelineModel221 var body: some View {222 VStack(alignment: .leading, spacing: 6) {223 if let e = data.error, !data.items.isEmpty { Banner(.danger, e) }224 if !data.sourceErrors.isEmpty {225 Banner(.warning, "Historique INCOMPLET — sources illisibles : " + data.sourceErrors.map { "\(OpsTimelineText.source($0.source)) (\($0.code))" }.joined(separator: ", ") + ". Des opérations peuvent manquer ci-dessous.")226 }227 if let a = data.audit, !a.intact { Banner(.danger, "La chaîne d’audit est rompue à l’événement \(a.brokenAt.map(String.init) ?? "?") : les lignes issues du journal d’audit ne sont plus prouvées intactes.") }228 if let b = data.bounds { Text("Le serveur remonte au plus \(b.perSource) lignes par source (\(b.plans) plans) : l’historique plus ancien n’apparaît pas ici. Aucun total n’est calculé entre modes.").font(.caption).foregroundStyle(.secondary) }229 }.padding(.bottom, data.sourceErrors.isEmpty && data.bounds == nil ? 0 : 6)230 }231}232233private struct OpsTimelineDetail: View {234 let item: TimelineItem235 var body: some View {236 let i = item237 ScrollView {238 VStack(alignment: .leading, spacing: 6) {239 HStack {240 Text("\(OpsTimelineText.kind(i.kind)) · \(Fmt.dateSeconds(i.at))").font(.headline)241 OpsBookTag(kind: OpsBookKind(mode: i.mode))242 if i.isSimulated { ProvenanceTag(p: .simulated, text: "Simulation — aucun fonds réel") }243 Spacer()244 }245 if i.mode == nil { Text("La source ne précise pas de quel argent il s’agit pour cette ligne.").font(.caption).foregroundStyle(.secondary) }246 Field(label: "Code", value: i.code, mono: true)247 Field(label: "Source", value: OpsTimelineText.source(i.source))248 Field(label: "État servi", value: OpsTimelineText.status(i))249 if let v = i.instrument { Field(label: "Instrument", value: v) }250 if let v = i.side { Field(label: "Sens", value: v) }251 if let v = OpsTimelineText.quantity(i.amount) { Field(label: "Montant", value: v) }252 if let v = OpsTimelineText.quantity(i.received) { Field(label: "Reçu", value: v) }253 if let v = i.venue { Field(label: "Plateforme", value: v) }254 if let v = i.network { Field(label: "Réseau", value: v) }255 Field(label: "Auteur", value: OpsTimelineText.principal(i.principal))256 Field(label: "Référence", value: "\(i.ref.type) \(i.ref.id)", mono: true)257 if let tx = i.txid {258 Field(label: "Identifiant de transaction", value: tx, mono: true)259 Text("Un identifiant de transaction n’est pas une confirmation : seul l’état servi fait foi.").font(.caption).foregroundStyle(.secondary)260 }261 if let ex = i.explorer, let url = URL(string: ex), url.scheme == "https" { Link("Ouvrir dans l’explorateur de blocs", destination: url) }262 if !i.params.isEmpty {263 Divider(); Text("Paramètres servis").font(.caption).foregroundStyle(.secondary)264 ForEach(i.params.keys.sorted(), id: \.self) { k in if let v = i.params[k] { Field(label: k, value: v.displayText, mono: true) } }265 }266 }.padding(16)267 }268 }269}270