Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/RsDataQualityTab.swift3// Description: The status of the server's market-data worker: which symbols and intervals it follows, the consolidation rule and source priority, its quality verdict per series (freshness, last bar, gaps, agreement between sources, confirmations) and the coverage stored per source. Shown as served; a verdict that is not "ok" is spelled out, never softened.4import SwiftUI5import SPWalletCore67@MainActor @Observable final class RsDataQualityModel {8 struct Coverage: Identifiable, Sendable {9 let source: String, symbol: String, interval: String10 let bars: Int?11 let first: Date?, last: Date?12 var id: String { "\(source)|\(symbol)|\(interval)" }13 }1415 let model: AppModel16 private let api: MarketsAPI17 private(set) var status: MarketDataStatus?18 private(set) var coverage: [Coverage] = []19 private(set) var loadedAt: Date?20 private(set) var loading = false21 private(set) var error: String?22 var symbolFilter = ""23 var onlyProblems = false2425 init(model: AppModel) { self.model = model; api = MarketsAPI(model.client) }2627 func load() async {28 guard !loading else { return }29 loading = true; defer { loading = false }30 do {31 let s = try await api.marketDataStatus()32 status = s; loadedAt = Date(); error = nil33 coverage = (s.coverage?.arrayValue ?? []).compactMap { c in34 guard let source = c["source"]?.stringValue, let symbol = c["symbol"]?.stringValue, let interval = c["interval"]?.stringValue else { return nil }35 return Coverage(source: source, symbol: symbol, interval: interval, bars: c["bars"]?.intValue.map(Int.init), first: RsFmt.date(ms: c["first"]), last: RsFmt.date(ms: c["last"]))36 }37 } catch { self.error = model.describe(error) }38 }3940 var quality: [MarketDataStatus.Quality] {41 let q = symbolFilter.trimmingCharacters(in: .whitespaces).uppercased()42 return (status?.quality ?? []).filter { (q.isEmpty || $0.symbol.uppercased().contains(q)) && (!onlyProblems || $0.status != "ok" || !$0.fresh) }43 }44 var shownCoverage: [Coverage] {45 let q = symbolFilter.trimmingCharacters(in: .whitespaces).uppercased()46 return coverage.filter { q.isEmpty || $0.symbol.uppercased().contains(q) }47 }48}4950enum RsQualityText {51 static func status(_ s: String) -> String {52 switch s {53 case "ok": "Utilisable"54 case "stale": "Périmée"55 case "gap": "Trou dans la série"56 case "insufficient_history": "Historique insuffisant"57 case "insufficient_sources": "Sources insuffisantes"58 case "disagreement": "Désaccord entre sources"59 case "no_data": "Aucune donnée"60 case "unsupported": "Non prise en charge"61 default: s62 }63 }64 static func failures(_ v: JSONValue?) -> String {65 guard let list = v?.arrayValue, !list.isEmpty else { return "—" }66 return list.map { f in f["message"]?.stringValue ?? f["code"]?.stringValue ?? f.displayText }.joined(separator: " ; ")67 }68 /// Confirmations: the sources that had the series, with their own last bar when the server gives it.69 static func sources(_ v: JSONValue?) -> String {70 guard let v, !v.isNull else { return "—" }71 if let o = v.objectValue {72 return o.keys.sorted().map { k in73 let s = o[k]; let last = RsFmt.date(ms: s?["lastTs"]).map { Fmt.date($0) } ?? "aucune barre"74 return "\(k) : \(s?["bars"]?.intValue.map { "\($0) barres" } ?? "—"), dernière \(last)\((s?["gaps"]?.intValue ?? 0) > 0 ? ", \(s?["gaps"]?.intValue ?? 0) trous" : "")"75 }.joined(separator: " · ").opsIfEmpty("—")76 }77 return RsJSONText.inline(v)78 }79}8081struct RsDataQualityTab: View {82 let model: AppModel83 @State private var data: RsDataQualityModel?8485 var body: some View {86 ScrollView {87 VStack(alignment: .leading, spacing: 16) {88 if let data {89 if let s = data.status {90 if let e = data.error { Banner(.warning, "Dernière lecture en échec (\(e)). L’état ci-dessous date du \(Fmt.date(data.loadedAt)).") }91 RsQualityOverview(data: data, status: s)92 RsQualityTable(data: data)93 RsCoverageCard(data: data)94 } else if let e = data.error { Card { OpsUnavailable(what: "État du collecteur de données de marché", reason: e) { Task { await data.load() } } } }95 else { ProgressView().frame(maxWidth: .infinity).padding(40) }96 } else { ProgressView() }97 }.padding(24).frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)98 }99 .task {100 let d = data ?? RsDataQualityModel(model: model); data = d101 await d.load()102 while !Task.isCancelled { // the server caches this answer for 30 s103 try? await Task.sleep(for: .seconds(60))104 guard !Task.isCancelled else { return }105 if AppActivity.isActive, !model.isOffline { await d.load() }106 }107 }108 }109}110111private struct RsQualityOverview: View {112 @Bindable var data: RsDataQualityModel113 let status: MarketDataStatus114115 var body: some View {116 let all = status.quality, ok = all.filter { $0.status == "ok" && $0.fresh }.count117 Card("Collecteur de données de marché", trailing: AnyView(HStack(spacing: 8) {118 if data.loading { ProgressView().controlSize(.small) }119 OpsAsOf(date: data.loadedAt, prefix: "Reçu")120 Button { Task { await data.load() } } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.borderless)121 })) {122 HStack(spacing: 22) {123 OpsMini(label: "Séries suivies", value: "\(all.count)")124 OpsMini(label: "Utilisables et fraîches", value: "\(ok)")125 OpsMini(label: "À problème", value: "\(all.count - ok)")126 OpsMini(label: "Symboles", value: "\(status.symbols.count)")127 OpsMini(label: "Intervalles", value: status.intervals.joined(separator: ", ").opsIfEmpty("—"))128 OpsMini(label: "Barres rejetées depuis le démarrage", value: RsJSONText.inline(status.rejectedSinceStart))129 }130 if all.count - ok > 0 { Banner(.warning, "\(all.count - ok) séries ne sont pas utilisables pour une décision selon le serveur : un agent qui en dépend attend, il ne décide pas sur une donnée douteuse.") }131 Field(label: "Règle de consolidation", value: status.rule)132 Field(label: "Priorité des sources", value: RsJSONText.inline(status.priority))133 Field(label: "Seuils de qualité", value: RsJSONText.inline(status.thresholds))134 if let sources = status.sources?.arrayValue, !sources.isEmpty {135 DisclosureGroup("Sources (\(sources.count))") {136 VStack(alignment: .leading, spacing: 4) {137 ForEach(Array(sources.enumerated()), id: \.offset) { _, s in138 Text("\(s["id"]?.stringValue ?? "?") — au plus \(RsJSONText.inline(s["maxBars"])) barres par requête ; historique accessible : \(s["historyBars"].map { $0.isNull ? "complet" : "\(RsJSONText.inline($0)) barres" } ?? "—") ; \(s["pairs"]?.objectValue?.count ?? 0) paires suivies")139 .font(.callout).frame(maxWidth: .infinity, alignment: .leading)140 }141 }.padding(.top, 4)142 }143 }144 HStack {145 TextField("Filtrer par symbole", text: $data.symbolFilter).textFieldStyle(.roundedBorder).frame(width: 200)146 Toggle("Seulement les séries à problème", isOn: $data.onlyProblems).toggleStyle(.checkbox)147 Spacer()148 }149 }150 }151}152153private struct RsQualityTable: View {154 let data: RsDataQualityModel155 @State private var selection: String?156157 var body: some View {158 let rows = data.quality.map(RsQualityRow.init)159 Card("Verdict de qualité par série", trailing: AnyView(ProvenanceTag(p: .verified, text: "Mesuré par le serveur"))) {160 Table(rows, selection: $selection) {161 TableColumn("Série") { r in Text("\(r.q.symbol) · \(r.q.interval)").fontWeight(.medium) }.width(min: 90, ideal: 110)162 TableColumn("Verdict") { r in163 Label(RsQualityText.status(r.q.status), systemImage: r.q.status == "ok" ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(r.q.status == "ok" ? Theme.positive : Theme.negative)164 }.width(min: 150, ideal: 180)165 TableColumn("Fraîcheur") { r in Text(r.q.fresh ? "Fraîche" : "Pas fraîche").foregroundStyle(r.q.fresh ? Color.secondary : Theme.warning) }.width(min: 80, ideal: 90)166 TableColumn("Dernière barre") { r in Text(RsFmt.date(ms: r.q.lastTs).map { Fmt.date($0) } ?? "aucune").monospacedDigit() }.width(min: 130, ideal: 150)167 TableColumn("Trous") { r in Text(RsJSONText.inline(r.q.gaps)).monospacedDigit().foregroundStyle((r.q.gaps?.intValue ?? 0) > 0 ? Theme.warning : .primary) }.width(50)168 TableColumn("Écart max entre sources") { r in Text(r.q.maxDeviationBps?.doubleValue.map { "\(OpsFmt.number($0, digits: 1)) pb" } ?? "non mesuré").monospacedDigit() }.width(min: 110, ideal: 140)169 TableColumn("Vérifiée") { r in Text(RsFmt.date(ms: r.q.checkedAt).map { Fmt.relative($0) } ?? "—").foregroundStyle(.secondary) }.width(min: 90, ideal: 110)170 }171 .frame(height: min(max(CGFloat(rows.count) * 28 + 34, 120), 420))172 .overlay { if rows.isEmpty { Text("Aucune série ne correspond.").foregroundStyle(.secondary) } }173 if let id = selection, let r = rows.first(where: { $0.id == id }) {174 Divider()175 Text("\(r.q.symbol) · \(r.q.interval)").font(.subheadline.weight(.semibold))176 Field(label: "Motifs du verdict", value: RsQualityText.failures(r.q.failures))177 Field(label: "Confirmations par source", value: RsQualityText.sources(r.q.sources))178 Field(label: "Barres fournies par source", value: RsJSONText.inline(r.q.provided))179 Field(label: "Fenêtre d’accord", value: RsJSONText.inline(r.q.window))180 } else { Text("Sélectionnez une série pour voir les motifs du verdict et les confirmations par source.").font(.caption).foregroundStyle(.secondary) }181 }182 }183}184185private struct RsQualityRow: Identifiable {186 let q: MarketDataStatus.Quality187 var id: String { "\(q.symbol)|\(q.interval)" }188}189190private struct RsCoverageCard: View {191 let data: RsDataQualityModel192 var body: some View {193 let rows = data.shownCoverage194 Card("Couverture enregistrée par source", trailing: AnyView(Text("\(rows.count) séries").font(.caption).foregroundStyle(.secondary))) {195 if data.coverage.isEmpty { Text("Le serveur ne rapporte aucune barre enregistrée.").foregroundStyle(.secondary) }196 else {197 Table(rows) {198 TableColumn("Source") { Text($0.source) }.width(min: 90, ideal: 110)199 TableColumn("Série") { Text("\($0.symbol) · \($0.interval)") }.width(min: 90, ideal: 110)200 TableColumn("Barres") { Text($0.bars.map { $0.formatted() } ?? "—").monospacedDigit() }.width(min: 70, ideal: 90)201 TableColumn("Première barre") { Text(Fmt.date($0.first)).monospacedDigit() }.width(min: 130, ideal: 160)202 TableColumn("Dernière barre") { Text(Fmt.date($0.last)).monospacedDigit() }.width(min: 130, ideal: 160)203 }.frame(height: min(max(CGFloat(rows.count) * 28 + 34, 120), 420))204 }205 }206 }207}208