Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/Dashboard/DashboardView.swift10// Description : The overview: estimated total, allocation, value history11// as observed by this Mac, pending and recent transactions,12// open derivative positions (real, testnet and paper books13// kept apart), unread alerts and the MacLustr connection14// state. Each block states where its figures come from; a15// block whose source failed says so instead of showing zero.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 Charts95import SPWalletCore9697struct DashboardView: View {98 let model: AppModel99 @Bindable var nav: Navigator100 @State private var summary: DashboardSummary?101 @State private var summaryError: String?102 @State private var unread: AlertUnread?103 @State private var history: [ValuePoint] = []104 @State private var range = 30105106 var body: some View {107 Page("Tableau de bord") {108 BalanceCard(model: model, nav: nav)109 statTiles110 HStack(alignment: .top, spacing: 16) {111 AllocationCard(model: model, by: .asset)112 AllocationCard(model: model, by: .network)113 }114 historyCard115 HStack(alignment: .top, spacing: 16) {116 recentCard117 VStack(spacing: 16) { connectionCard; alertsCard }118 }119 positionsCard120 }121 .task(id: model.portfolio?.fetchedAt) { await load() }122 }123124 private func load() async {125 history = await ValueHistory.shared.series(currency: model.currency, since: Date().addingTimeInterval(-Double(range) * 86400))126 guard model.phase == .signedIn, !model.isOffline else { return }127 do { summary = try await DashboardAPI(model.client).summary(); summaryError = nil } catch { summaryError = model.describe(error) }128 unread = try? await AlertsAPI(model.client).unread()129 }130131 private var statTiles: some View {132 let p = model.portfolio?.value133 let held = p?.balances.filter(\.isNonZero) ?? []134 let (level, text) = SecurityIndicator.assess(model)135 let nets = model.health?.value.networks ?? []136 let bad = nets.filter { $0.ok == false }.count137 return HStack(spacing: 14) {138 StatTile(symbol: "circle.hexagongrid.fill", label: "Actifs détenus", value: p == nil ? "—" : "\(held.count)", tint: Theme.series(0), detail: p == nil ? nil : "sur \(Set(held.map(\.network)).count) réseau(x)")139 StatTile(symbol: "network", label: "Réseaux joignables", value: nets.isEmpty ? "—" : "\(nets.count - bad) / \(nets.count)", tint: bad == 0 ? Theme.series(1) : Theme.warning, detail: nets.isEmpty ? "non mesuré" : bad == 0 ? "tous les RPC répondent" : "\(bad) RPC en échec")140 StatTile(symbol: "arrow.triangle.2.circlepath", label: "Opérations en cours", value: p == nil ? "—" : "\(p!.pending.count)", tint: Theme.series(4), detail: (p?.pending.isEmpty ?? true) ? "aucune en attente" : "à suivre dans Activité")141 StatTile(symbol: level.symbol, label: "Signataire isolé", value: level == .ok ? "Prêt" : level == .blocked ? "Arrêté" : level == .degraded ? "Dégradé" : "Inconnu", tint: level.color, detail: text)142 }143 }144145 private var historyCard: some View {146 Card("Historique de la valeur estimée", trailing: AnyView(Picker("", selection: $range) { Text("7 j").tag(7); Text("30 j").tag(30); Text("1 an").tag(365) }.pickerStyle(.segmented).frame(width: 170).onChange(of: range) { Task { await load() } })) {147 if history.count >= 2 {148 Chart(history) { p in149 AreaMark(x: .value("Date", p.at), y: .value("Valeur", p.value)).interpolationMethod(.linear)150 .foregroundStyle(LinearGradient(colors: [Theme.azure.opacity(0.28), Theme.azure.opacity(0.02)], startPoint: .top, endPoint: .bottom))151 LineMark(x: .value("Date", p.at), y: .value("Valeur", p.value)).interpolationMethod(.linear).foregroundStyle(Theme.azure).lineStyle(StrokeStyle(lineWidth: 2.2, lineCap: .round, lineJoin: .round))152 if !p.complete { PointMark(x: .value("Date", p.at), y: .value("Valeur", p.value)).foregroundStyle(Theme.warning).symbolSize(18) }153 }154 .chartYScale(domain: .automatic(includesZero: false)).frame(height: 190)155 .chartXAxis { AxisMarks { _ in AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: [3, 3])); AxisValueLabel() } }156 .chartYAxis { AxisMarks { v in AxisGridLine(); AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.compact(d, model.currency)) } } } }157 } else {158 Text("Pas encore assez de points.").foregroundStyle(.secondary).frame(height: 60)159 }160 Text("Estimations (soldes × prix affichés) relevées par ce Mac quand l’app était ouverte ; le serveur ne conserve pas cette série. Les interruptions sont de vraies absences de mesure\(history.contains { !$0.complete } ? " ; points orange = total incomplet" : "").").font(.caption).foregroundStyle(.secondary)161 }162 }163164 private var recentCard: some View {165 Card("Transactions", trailing: AnyView(Button("Tout voir") { nav.section = .activity }.buttonStyle(.link))) {166 let pending = model.portfolio?.value.pending ?? []167 if !pending.isEmpty {168 Text("En cours").font(.caption).foregroundStyle(.secondary)169 ForEach(pending) { p in170 HStack { Text("\(Fmt.amount(p.amountDisplay, maxFraction: 8)) \(p.symbol) · \(p.networkName ?? p.network)"); Spacer(); StatusPill(raw: p.state.rawValue) }171 }172 Divider()173 }174 let items = (model.activity?.value ?? []).prefix(6)175 if items.isEmpty { Text(model.activity == nil ? "Historique non synchronisé." : "Aucune transaction.").foregroundStyle(.secondary) }176 ForEach(Array(items)) { TransactionRow(item: $0) }177 }178 }179180 private var connectionCard: some View {181 Card("Connexion MacLustr") {182 SecurityIndicator(model: model)183 if let h = model.health?.value {184 let bad = h.networks.filter { $0.ok == false }185 Field(label: "Base de données", value: h.db ? "joignable" : "en échec")186 Field(label: "Réseaux (RPC)", value: bad.isEmpty ? "\(h.networks.count) joignables" : "\(bad.count) en échec sur \(h.networks.count) : " + bad.compactMap(\.network).joined(separator: ", "))187 Text("Relevé \(Fmt.relative(model.health?.fetchedAt))").font(.caption).foregroundStyle(.secondary)188 } else { Text("État des réseaux non lu.").foregroundStyle(.secondary) }189 if case .ok(let d, _)? = summary?.health, !d.connectors.failing.isEmpty {190 Text("Connecteurs en échec : " + d.connectors.failing.map(\.name).joined(separator: ", ")).font(.callout).foregroundStyle(Theme.warning)191 }192 }193 }194195 private var alertsCard: some View {196 Card("Alertes", trailing: AnyView(Button("Ouvrir") { nav.section = .alerts }.buttonStyle(.link))) {197 if let u = unread {198 HStack(spacing: 16) {199 Label("\(u.unread) non lue(s)", systemImage: "bell").foregroundStyle(u.unread > 0 ? .primary : .secondary)200 if u.critical > 0 { Label("\(u.critical) critique(s)", systemImage: "exclamationmark.octagon.fill").foregroundStyle(Theme.negative) }201 }202 } else { Text("Compteur d’alertes non lu.").foregroundStyle(.secondary) }203 if case .ok(let r, _)? = summary?.risk {204 if r.switches.killSwitch.on { Banner(.danger, "Arrêt global du trading engagé\(r.switches.killSwitch.reason.map { " : \($0)" } ?? "").") }205 if r.switches.readOnly.on { Banner(.warning, "Trading en lecture seule.") }206 }207 }208 }209210 @ViewBuilder private var positionsCard: some View {211 Card("Positions ouvertes (dérivés)", trailing: AnyView(Button("Contrats à terme") { nav.section = .futures }.buttonStyle(.link))) {212 if let s = summary {213 bookRows("Réel", s.books.live, color: Theme.negative)214 bookRows("Testnet", s.books.liveTestnet, color: Theme.warning)215 bookRows("Simulation (papier)", s.books.paper, color: .secondary)216 Text("Trois livres séparés : aucun chiffre du papier ou du testnet n’est additionné au réel.").font(.caption).foregroundStyle(.secondary)217 } else if let e = summaryError { Text("Indisponible : \(e)").foregroundStyle(.secondary) }218 else { Text(model.canOperate ? "Lecture…" : "Indisponible hors connexion.").foregroundStyle(.secondary) }219 }220 }221 @ViewBuilder private func bookRows(_ title: String, _ sec: DashboardSection<DashboardBook>, color: Color) -> some View {222 HStack { Text(title).font(.callout.weight(.semibold)).foregroundStyle(color); Spacer()223 if let a = sec.asOf { Text("relevé \(Fmt.relative(a))").font(.caption).foregroundStyle(.secondary) } }224 switch sec {225 case .failed(let code, _): Label("Indisponible (\(code)) — ce n’est pas « aucune position ».", systemImage: "xmark.octagon").foregroundStyle(Theme.warning).font(.callout)226 case .ok(let b, _):227 if b.positions.isEmpty { Text("Aucune position.").foregroundStyle(.secondary).font(.callout) }228 ForEach(b.positions, id: \.self) { p in229 HStack {230 Text("\(p.instrument) · \(p.venue)").frame(width: 220, alignment: .leading)231 Text(p.side == "long" ? "LONG" : "SHORT").font(.caption.weight(.bold)).foregroundStyle(p.side == "long" ? Theme.positive : Theme.negative).frame(width: 50)232 Text("\(Fmt.amount(p.size, maxFraction: 6)) · notionnel \(Fmt.amount(p.notional, maxFraction: 2)) $ · levier \(Fmt.amount(p.leverage, maxFraction: 2))×").monospacedDigit()233 Spacer()234 Text("liq. \(p.liquidationPrice.map { Fmt.amount($0, maxFraction: 4) } ?? "—")").foregroundStyle(Theme.warning).monospacedDigit()235 Text("PnL latent \(Fmt.amount(p.unrealizedPnl, maxFraction: 2)) $").monospacedDigit().foregroundStyle(p.unrealizedPnl.hasPrefix("-") ? Theme.negative : Theme.positive)236 }.font(.callout)237 }238 if !b.isComplete { Text("Lecture partielle : \(b.errors.joined(separator: " ; "))").font(.caption).foregroundStyle(Theme.warning) }239 }240 }241}242243/// Share of the estimated total per asset or per network (an estimate: balances × prices).244struct AllocationCard: View {245 enum Axis { case asset, network }246 let model: AppModel247 let by: Axis248 struct Slice: Identifiable { let id: String; let value: Double }249250 var slices: [Slice] {251 guard let p = model.portfolio?.value, p.prices != nil, model.settings.prices else { return [] }252 var sums: [String: Double] = [:]253 for b in p.balances { if let v = p.estimatedValue(of: b, in: model.currency), v > 0 { sums[by == .asset ? b.symbol : b.networkName, default: 0] += v } }254 let sorted = sums.sorted { $0.value > $1.value }255 let top = sorted.prefix(7).map { Slice(id: $0.key, value: $0.value) }256 let rest = sorted.dropFirst(7).reduce(0) { $0 + $1.value }257 return rest > 0 ? top + [Slice(id: "Autres", value: rest)] : top258 }259 var body: some View {260 Card(by == .asset ? "Répartition par actif" : "Répartition par blockchain", trailing: AnyView(ProvenanceTag(p: .estimate))) {261 let s = slices; let total = s.reduce(0) { $0 + $1.value }262 if s.isEmpty { Text("Aucune valeur estimable (pas de solde, ou prix indisponibles).").foregroundStyle(.secondary).frame(height: 150) }263 else {264 HStack(spacing: 20) {265 Chart(Array(s.enumerated()), id: \.element.id) { i, x in266 SectorMark(angle: .value("Valeur", x.value), innerRadius: .ratio(0.68), angularInset: 1.5).cornerRadius(4).foregroundStyle(Theme.series(i))267 }268 .chartLegend(.hidden).frame(width: 150, height: 150).opacity(model.settings.hideBalances ? 0.25 : 1)269 .overlay { VStack(spacing: 0) { Text("\(s.count)").font(Theme.figure(24)); Text(by == .asset ? "actifs" : "réseaux").font(.caption2).foregroundStyle(.secondary) } }270 VStack(alignment: .leading, spacing: 7) {271 ForEach(Array(s.enumerated()), id: \.element.id) { i, x in272 HStack(spacing: 8) {273 RoundedRectangle(cornerRadius: 3).fill(Theme.series(i)).frame(width: 10, height: 10)274 Text(x.id).lineLimit(1)275 Spacer()276 Text((x.value / total).formatted(.percent.precision(.fractionLength(1)))).monospacedDigit().foregroundStyle(.secondary)277 Text(model.settings.hideBalances ? "••••" : Fmt.fiat(x.value, model.currency, estimate: false)).monospacedDigit().fontWeight(.medium).frame(width: 110, alignment: .trailing)278 }.font(.callout)279 }280 }281 }282 }283 }284 }285}286