Repository Public
1//2// VQuant iOS3// File: VQuant/Next/TerminalViews.swift4// Description: The terminal: market overview by section with freshness chips, the Treasury yield curve, the economic5// calendar, the universal search, financial statements and the health of the data providers.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Charts12import SwiftUI13import VQuantKit14import VQuantUI1516struct TerminalView: View {17 @Environment(AppModel.self) private var model18 @Environment(\.horizontalSizeClass) private var sizeClass19 @State private var moverGroup = "gainers"2021 var body: some View {22 ScrollView {23 VStack(alignment: .leading, spacing: 22) {24 OfflineBanner().clipShape(RoundedRectangle(cornerRadius: 10))25 if let o = model.next.terminal.overview.value {26 status(o)27 CachedNotice(at: model.next.terminal.overview.cachedAt)28 ForEach(o.sections) { section in sectionView(section) }29 if let curve = o.yieldCurve { YieldCurveCard(curve: curve) }30 if !o.calendar.isEmpty { calendar(o) }31 } else if model.next.terminal.overview.isUnavailable {32 StateView(kind: .failed, title: "Vue des marchés indisponible", message: model.next.terminal.overview.error) { Task { await model.next.terminal.refreshOverview() } }33 } else {34 VQLoading("Chargement de la vue des marchés") { VStack(alignment: .leading, spacing: 16) { VQSkeletonRows(rows: 4, columns: 3); VQSkeletonChart() } }35 }36 }37 .padding(16)38 .frame(maxWidth: 1180).frame(maxWidth: .infinity)39 }40 .background(Theme.background)41 .navigationTitle("Terminal")42 .toolbar {43 ToolbarItem(placement: .topBarTrailing) {44 RouteLink(.dataHealth) { Label("Fournisseurs de données", systemImage: "stethoscope") }.accessibilityIdentifier("terminal-health")45 }46 }47 .task { if model.next.terminal.overview.value == nil { await model.next.terminal.refreshOverview() } }48 .refreshable { await model.next.terminal.refreshOverview() }49 .accessibilityIdentifier("terminal")50 }5152 private func status(_ o: VQMarketOverview) -> some View {53 HStack(alignment: .firstTextBaseline, spacing: 10) {54 Tag(text: Self.sessionLabel(o.status), systemImage: o.status.isOpen ? "sun.max" : "moon", color: o.status.isOpen ? Theme.up : Theme.textSecondary)55 if let n = o.status.note, !n.isEmpty { Text(n).font(.caption).foregroundStyle(Theme.textSecondary) }56 Spacer(minLength: 0)57 if let a = o.asOf { Text("Vue du \(Fmt.dateTime(a))").font(.caption).foregroundStyle(Theme.textSecondary) }58 }59 .accessibilityElement(children: .combine)60 }61 static func sessionLabel(_ s: VQMarketOverview.Status) -> String {62 switch s.session.known { case .pre: "Avant-bourse"; case .regular: "Séance ouverte"; case .post: "Après-bourse"; case .closed: "Séance fermée"; case nil: s.isOpen ? "Ouvert" : "Fermé" }63 }64 static func title(_ s: VQMarketOverview.Section) -> String {65 switch s.id {66 case "indices": "Indices"; case "sectors": "Secteurs"; case "rates": "Taux"; case "fx": "Devises"; case "commodities": "Matières premières"67 case "crypto": "Cryptoactifs"; case "volatility": "Volatilité"; case "movers": "Mouvements du jour"; default: s.title68 }69 }7071 @ViewBuilder private func sectionView(_ s: VQMarketOverview.Section) -> some View {72 VStack(alignment: .leading, spacing: 10) {73 EditorialHeader(Self.title(s)) { if let f = s.freshness { ProvenanceChip(f) } }74 if !s.available || s.items.isEmpty {75 Label(s.freshness?.note ?? "Section indisponible chez le fournisseur.", systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.textSecondary)76 } else if s.id == "sectors" {77 SectorBars(items: s.items)78 } else if s.id == "movers" {79 Picker("Mouvements", selection: $moverGroup) { Text("Hausses").tag("gainers"); Text("Baisses").tag("losers"); Text("Volumes").tag("actives") }.pickerStyle(.segmented)80 let list = s.items.filter { $0.group == moverGroup }81 VStack(spacing: 0) {82 ForEach(list.prefix(8)) { item in83 if let sym = item.symbol {84 RouteLink(.asset(sym)) { OverviewRow(item: item).padding(.vertical, 8) }.buttonStyle(.plain).draggableSymbol(sym)85 } else { OverviewRow(item: item).padding(.vertical, 8) }86 Divider()87 }88 }89 } else {90 LazyVGrid(columns: [GridItem(.adaptive(minimum: sizeClass == .regular ? 170 : 150), spacing: 10)], spacing: 10) {91 ForEach(s.items) { item in92 if let sym = item.symbol, !sym.hasPrefix("UST") {93 RouteLink(.asset(sym)) { OverviewTile(item: item) }.buttonStyle(.plain).draggableSymbol(sym)94 } else { OverviewTile(item: item) }95 }96 }97 }98 }99 .accessibilityElement(children: .contain).accessibilityIdentifier("terminal-\(s.id)")100 }101102 private func calendar(_ o: VQMarketOverview) -> some View {103 VStack(alignment: .leading, spacing: 10) {104 EditorialHeader("Calendrier économique") { if let f = o.calendarFreshness { ProvenanceChip(f) } }105 VStack(spacing: 0) {106 ForEach(Array(o.calendar.prefix(14).enumerated()), id: \.offset) { _, e in107 HStack(alignment: .top, spacing: 10) {108 VStack(alignment: .leading, spacing: 2) {109 Text(e.when.map { Fmt.dateTime($0) } ?? e.date).font(.mono(.caption2)).foregroundStyle(Theme.textSecondary)110 Text(e.event).font(.subheadline).fixedSize(horizontal: false, vertical: true)111 Text([e.country, e.impact.map { "impact \($0.lowercased())" }].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.textSecondary)112 }113 Spacer(minLength: 8)114 VStack(alignment: .trailing, spacing: 2) {115 Text(e.actual.map { VQFormat.number($0, decimals: 2) + (e.unit ?? "") } ?? "à venir").font(.mono(.footnote, weight: .medium))116 if let est = e.estimate { Text("prévu \(VQFormat.number(est, decimals: 2))").font(.mono(.caption2)).foregroundStyle(Theme.textSecondary) }117 if let prev = e.previous { Text("préc. \(VQFormat.number(prev, decimals: 2))").font(.mono(.caption2)).foregroundStyle(Theme.textSecondary) }118 }119 }120 .padding(.vertical, 8)121 .accessibilityElement(children: .combine)122 Divider()123 }124 }125 }126 .accessibilityElement(children: .contain).accessibilityIdentifier("terminal-calendar")127 }128}129130struct OverviewRow: View {131 let item: VQMarketOverview.Item132 var body: some View {133 HStack(spacing: 12) {134 VStack(alignment: .leading, spacing: 2) {135 Text(item.symbol ?? item.name).font(.body.weight(.semibold))136 if item.symbol != nil { Text(item.name).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(1) }137 }138 Spacer(minLength: 8)139 VStack(alignment: .trailing, spacing: 2) {140 Text(OverviewTile.level(item)).font(.mono(.callout, weight: .medium))141 ChangeLabel(percent: item.changePct, font: .caption)142 }143 }144 .contentShape(Rectangle())145 .accessibilityElement(children: .combine)146 }147}148149/// Sector changes as bars around zero (average change of listed stocks, as the server states).150struct SectorBars: View {151 let items: [VQMarketOverview.Item]152 var body: some View {153 let sorted = items.sorted { ($0.changePct ?? 0) > ($1.changePct ?? 0) }154 let scale = max(0.01, sorted.compactMap { $0.changePct.map(abs) }.max() ?? 1)155 VStack(spacing: 6) {156 ForEach(sorted) { item in157 HStack(spacing: 8) {158 Text(item.name).font(.caption).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)159 GeometryReader { geo in160 let v = item.changePct ?? 0161 let w = geo.size.width / 2 * CGFloat(abs(v) / scale)162 ZStack(alignment: .leading) {163 Rectangle().fill(Theme.border).frame(width: 1).offset(x: geo.size.width / 2)164 Rectangle().fill(Theme.direction(v)).frame(width: max(1, w), height: 10).offset(x: v >= 0 ? geo.size.width / 2 : geo.size.width / 2 - w)165 }166 .frame(maxHeight: .infinity)167 }168 .frame(width: 110, height: 16)169 Text(Fmt.percent(item.changePct)).font(.mono(.caption)).foregroundStyle(Theme.direction(item.changePct)).frame(width: 72, alignment: .trailing)170 }171 .accessibilityElement(children: .ignore)172 .accessibilityAddTraits(.isStaticText)173 .accessibilityLabel("\(item.name), \(Fmt.percent(item.changePct))")174 }175 }176 }177}178179struct YieldCurveCard: View {180 let curve: VQMarketOverview.YieldCurve181 private struct P: Identifiable { var tenor: String; var months: Double; var value: Double; var series: String; var id: String { series + tenor } }182183 var body: some View {184 let now = curve.points.compactMap { p in p.yield.map { P(tenor: p.tenor, months: p.months, value: $0, series: "Le \(curve.date)") } }185 let before = (curve.previous?.points ?? []).compactMap { p in p.yield.map { P(tenor: p.tenor, months: p.months, value: $0, series: "Le \(curve.previous?.date ?? "")") } }186 VStack(alignment: .leading, spacing: 10) {187 EditorialHeader("Courbe des taux du Trésor américain") { if let f = curve.freshness { ProvenanceChip(f) } }188 Chart {189 ForEach(before) { p in190 LineMark(x: .value("Échéance", p.tenor), y: .value("Rendement", p.value), series: .value("Date", p.series))191 .foregroundStyle(Theme.textSecondary).lineStyle(StrokeStyle(lineWidth: 1.2, dash: [4, 3]))192 }193 ForEach(now) { p in194 LineMark(x: .value("Échéance", p.tenor), y: .value("Rendement", p.value), series: .value("Date", p.series))195 .foregroundStyle(VQTokens.DataPalette.categorical[0]).lineStyle(StrokeStyle(lineWidth: 2))196 PointMark(x: .value("Échéance", p.tenor), y: .value("Rendement", p.value)).foregroundStyle(VQTokens.DataPalette.categorical[0]).symbolSize(26)197 }198 }199 .chartXScale(domain: curve.points.map(\.tenor))200 .chartYScale(domain: .automatic(includesZero: false))201 .chartYAxis { AxisMarks(position: .leading) { v in AxisGridLine(); AxisValueLabel { if let d = v.as(Double.self) { Text(VQFormat.number(d, decimals: 2) + " %").font(.mono(.caption2)) } } } }202 .frame(height: 220)203 .accessibilityLabel("Courbe des taux")204 .accessibilityValue(now.map { "\($0.tenor) \(VQFormat.number($0.value, decimals: 2)) %" }.joined(separator: ", "))205 HStack(spacing: 14) {206 legend("Le \(curve.date)", color: VQTokens.DataPalette.categorical[0], dashed: false)207 if let p = curve.previous { legend("Le \(p.date)", color: Theme.textSecondary, dashed: true) }208 }209 Text("Rendements observés, en pour cent.").font(.caption).foregroundStyle(Theme.textSecondary)210 }211 .accessibilityElement(children: .contain).accessibilityIdentifier("terminal-yield-curve")212 }213 private func legend(_ text: String, color: Color, dashed: Bool) -> some View {214 HStack(spacing: 5) {215 Rectangle().fill(color).frame(width: dashed ? 6 : 14, height: 2)216 if dashed { Rectangle().fill(color).frame(width: 6, height: 2) }217 Text(text).font(.caption).foregroundStyle(Theme.textSecondary)218 }219 }220}221222// MARK: - Universal search223224/// One search over symbols (ticker, name, ISIN), the person's conversations, projects, notes, lists, portfolios and225/// charts, navigation targets and Quant Lab engines (`/api/v2/search`).226struct UniversalSearchSheet: View {227 @Environment(AppModel.self) private var model228 @Environment(\.dismiss) private var dismiss229 @Environment(\.horizontalSizeClass) private var sizeClass230 @State private var query = ""231 @State private var results: VQSearchResults?232 @State private var error: String?233 @State private var searching = false234 @FocusState private var focused: Bool235236 var body: some View {237 NavigationStack {238 List {239 if let error { Label(error, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down) }240 if let r = results {241 if r.unavailable.contains("symbol") {242 Label("La recherche de symboles est momentanément indisponible chez le fournisseur ; les autres résultats sont complets.", systemImage: "clock.badge.exclamationmark").font(.footnote).foregroundStyle(Theme.warning)243 }244 if r.results.isEmpty, !searching { Text(query.isEmpty ? "Tapez un symbole, un nom de société, un ISIN, un titre d’analyse ou de note." : "Aucun résultat pour « \(query) ».").foregroundStyle(Theme.textSecondary) }245 ForEach(r.results) { item in246 Button { open(item) } label: { SearchResultRow(result: item) }247 .buttonStyle(.plain)248 .accessibilityIdentifier("search-\(item.type.rawValue)-\(item.resultId)")249 }250 } else if searching { ProgressView() }251 }252 .listStyle(.plain)253 .navigationTitle("Rechercher").navigationBarTitleDisplayMode(.inline)254 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Symbole, société, ISIN, analyse, note, moteur…")255 .autocorrectionDisabled()256 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.keyboardShortcut(.cancelAction) } }257 .task(id: query) { await search() }258 }259 .accessibilityIdentifier("universal-search")260 }261262 private func search() async {263 let text = query.trimmingCharacters(in: .whitespaces)264 if !text.isEmpty { try? await Task.sleep(for: .milliseconds(280)); if Task.isCancelled { return } }265 searching = true; defer { searching = false }266 do { results = try await model.next.terminal.search(text); error = nil }267 catch { if !Task.isCancelled { self.error = nextMessage(error) } }268 }269270 private func open(_ r: VQSearchResult) {271 dismiss()272 SearchRouting.open(r, router: model.router, compact: sizeClass == .compact)273 }274}275276struct SearchResultRow: View {277 let result: VQSearchResult278 var body: some View {279 HStack(spacing: 12) {280 Image(systemName: SearchRouting.icon(result)).foregroundStyle(Theme.orange).frame(width: 24)281 VStack(alignment: .leading, spacing: 2) {282 Text(result.title).font(.body.weight(.medium)).lineLimit(2)283 Text([SearchRouting.kind(result), result.symbol == result.title ? nil : result.symbol, result.subtitle, result.exchange].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))284 .font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(1)285 }286 Spacer(minLength: 0)287 }288 .frame(minHeight: 44).contentShape(Rectangle())289 .accessibilityElement(children: .combine)290 }291}292293// MARK: - Statements294295/// Income statement, balance sheet, cash flow, ratios, growth and common size from `/api/v2/data/statements`: rows296/// by period (newest first), each derived row with its formula.297struct StatementsView: View {298 let symbol: String299 @Environment(AppModel.self) private var model300 @State private var period = "annual"301 @State private var table = "income"302 @State private var state = NextState<VQStatements>()303 @State private var formula: VQStatements.Row?304305 private static let tables: [(id: String, label: String)] = [("income", "Résultat"), ("balance", "Bilan"), ("cashflow", "Flux"), ("ratios", "Ratios"), ("growth", "Croissance"), ("common", "Structure")]306307 var body: some View {308 ScrollView {309 VStack(alignment: .leading, spacing: 14) {310 Picker("Période", selection: $period) { Text("Annuel").tag("annual"); Text("Trimestriel").tag("quarter") }.pickerStyle(.segmented)311 .accessibilityIdentifier("statements-period")312 ScrollView(.horizontal, showsIndicators: false) {313 HStack(spacing: 8) {314 ForEach(Self.tables, id: \.id) { t in315 Button(t.label) { table = t.id }316 .buttonStyle(.plain).font(.subheadline.weight(table == t.id ? .semibold : .regular))317 .padding(.horizontal, 12).frame(minHeight: 44)318 .background(table == t.id ? Theme.surface2 : .clear, in: Capsule())319 .overlay(Capsule().strokeBorder(Theme.border, lineWidth: 1))320 .accessibilityAddTraits(table == t.id ? [.isSelected] : [])321 .accessibilityIdentifier("statements-\(t.id)")322 }323 }324 }325 if let s = state.value {326 HStack {327 if let f = s.provenance?.freshness { ProvenanceChip(f) }328 CachedNotice(at: state.cachedAt)329 Spacer()330 if let c = s.currency { Text("Montants en \(c)").font(.caption).foregroundStyle(Theme.textSecondary) }331 }332 let rows = Self.rows(s, table)333 if rows.isEmpty { Text("Aucune ligne pour ce tableau.").font(.footnote).foregroundStyle(Theme.textSecondary) }334 else { StatementGrid(statements: s, rows: rows) { formula = $0 } }335 ForEach(s.provenance?.notes ?? [], id: \.self) { Text($0).font(.caption).foregroundStyle(Theme.textSecondary) }336 } else if state.isUnavailable {337 StateView(kind: .failed, title: "États financiers indisponibles", message: state.error) { Task { await load() } }338 } else { VQLoading("Chargement des états financiers") { VQSkeletonRows(rows: 8, columns: 4) } }339 }340 .padding(16)341 }342 .background(Theme.background)343 .navigationTitle("États financiers — \(symbol)").navigationBarTitleDisplayMode(.inline)344 .task(id: period) { await load() }345 .refreshable { await load() }346 .sheet(item: $formula) { row in347 NavigationStack {348 VStack(alignment: .leading, spacing: 12) {349 Text(row.label).font(.serif(.title3))350 Text("Ligne calculée par le serveur").font(.caption).foregroundStyle(Theme.textSecondary)351 Text(row.formula ?? "").font(.mono(.footnote)).textSelection(.enabled)352 Text("Une valeur est absente quand une donnée d’entrée manque, que le dénominateur est nul ou sans signification.").font(.caption).foregroundStyle(Theme.textSecondary)353 Spacer()354 }355 .padding(20).frame(maxWidth: .infinity, alignment: .leading)356 .navigationTitle("Formule").navigationBarTitleDisplayMode(.inline)357 }358 .presentationDetents([.medium])359 }360 .accessibilityIdentifier("statements")361 }362363 static func rows(_ s: VQStatements, _ table: String) -> [VQStatements.Row] {364 switch table {365 case "income": s.income; case "balance": s.balance; case "cashflow": s.cashflow; case "ratios": s.ratios; case "growth": s.growth366 default: s.commonSizeIncome + s.commonSizeBalance367 }368 }369370 private func load() async {371 state.begin()372 do { state.succeed(try await model.next.terminal.statements(symbol, period: period)) } catch { state.fail(error) }373 }374}375376struct StatementGrid: View {377 let statements: VQStatements378 let rows: [VQStatements.Row]379 /// Narrow columns for a workspace panel.380 var compact = false381 var onFormula: (VQStatements.Row) -> Void382 @ScaledMetric(relativeTo: .caption) private var wideLabel: CGFloat = 168383 @ScaledMetric(relativeTo: .caption) private var wideCell: CGFloat = 92384 @ScaledMetric(relativeTo: .caption) private var narrowLabel: CGFloat = 112385 @ScaledMetric(relativeTo: .caption) private var narrowCell: CGFloat = 78386 private var labelWidth: CGFloat { compact ? narrowLabel : wideLabel }387 private var cellWidth: CGFloat { compact ? narrowCell : wideCell }388389 var body: some View {390 HStack(alignment: .top, spacing: 0) {391 // The label column stays in place; the periods scroll.392 VStack(alignment: .leading, spacing: 0) {393 Text("Ligne").font(.caption2.weight(.semibold)).foregroundStyle(Theme.textSecondary).frame(height: 34, alignment: .leading)394 ForEach(rows) { r in395 Group {396 if r.formula != nil {397 Button { onFormula(r) } label: {398 HStack(spacing: 4) { Text(r.label).lineLimit(2).multilineTextAlignment(.leading); Image(systemName: "function").imageScale(.small).foregroundStyle(Theme.orange) }399 }400 .buttonStyle(.plain).accessibilityHint("Afficher la formule")401 } else { Text(r.label).lineLimit(2) }402 }403 .font(.caption).frame(width: labelWidth, height: 44, alignment: .leading)404 Divider().frame(width: labelWidth)405 }406 }407 ScrollView(.horizontal, showsIndicators: true) {408 VStack(alignment: .leading, spacing: 0) {409 HStack(spacing: 0) {410 ForEach(Array(statements.periods.enumerated()), id: \.offset) { _, p in411 VStack(alignment: .trailing, spacing: 0) { Text(p.label.isEmpty ? p.date : p.label).font(.caption2.weight(.semibold)); Text(p.date).font(.mono(.caption2)).foregroundStyle(Theme.textSecondary) }412 .frame(width: cellWidth, height: 34, alignment: .trailing)413 }414 }415 ForEach(rows) { r in416 HStack(spacing: 0) {417 ForEach(Array(statements.periods.indices), id: \.self) { i in418 let v: Double? = i < r.values.count ? r.values[i] : nil419 Text(Self.format(v, r)).font(.mono(.caption)).foregroundStyle(v == nil ? Theme.textSecondary : Color.primary)420 .frame(width: cellWidth, height: 44, alignment: .trailing)421 }422 }423 Divider()424 }425 }426 }427 }428 .accessibilityIdentifier("statement-grid")429 }430431 /// `percent` and `ratio` values are fractions (0.25 = 25 %): the contract's convention, formatted by the kit.432 static func format(_ v: Double?, _ r: VQStatements.Row) -> String {433 switch r.unit.known {434 case .currency: VQFormat.compact(v, decimals: 2)435 case .percent: VQFormat.percent(v, decimals: 1)436 case .ratio: VQFormat.number(v, decimals: 2)437 case .perShare: VQFormat.number(v, decimals: 2)438 case .count: VQFormat.compact(v, decimals: 2)439 case nil: VQFormat.number(v, decimals: 2)440 }441 }442}443444// MARK: - Data providers445446struct DataHealthView: View {447 @Environment(AppModel.self) private var model448 var body: some View {449 List {450 if let h = model.next.terminal.health.value {451 ForEach(h.providers) { p in452 Section {453 ForEach(p.capabilities) { c in454 HStack {455 Image(systemName: c.ok ? "checkmark.circle" : "xmark.circle").foregroundStyle(c.ok ? Theme.up : Theme.down)456 VStack(alignment: .leading, spacing: 2) {457 Text(c.label).font(.subheadline)458 if let d = c.detail, !d.isEmpty { Text(d).font(.caption).foregroundStyle(Theme.textSecondary) }459 }460 Spacer()461 if let ms = c.latencyMs { Text(VQFormat.duration(ms: ms)).font(.mono(.caption)).foregroundStyle(Theme.textSecondary) }462 }463 .accessibilityElement(children: .combine)464 }465 if let n = p.notes, !n.isEmpty { Text(n).font(.caption).foregroundStyle(Theme.textSecondary) }466 if let e = p.lastError { Label(e, systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.warning) }467 } header: {468 HStack { Text(p.name); Spacer(); Text(!p.configured ? "non configuré" : p.ok ? "disponible" : "en panne").foregroundStyle(p.ok ? Theme.up : Theme.down) }469 }470 }471 } else if model.next.terminal.health.isUnavailable {472 StateView(kind: .failed, title: "État des fournisseurs indisponible", message: model.next.terminal.health.error) { Task { await model.next.terminal.refreshHealth() } }473 } else { ProgressView() }474 }475 .navigationTitle("Fournisseurs de données")476 .task { await model.next.terminal.refreshHealth() }477 .refreshable { await model.next.terminal.refreshHealth() }478 .accessibilityIdentifier("data-health")479 }480}481