SPB Git

Repository Public

HomeView.swift 21.6 KB 408 lines swift

1//2//  VQuant iOS3//  File: VQuant/Features/Home/HomeView.swift4//  Description: Home dashboard: indices, watchlist, portfolio summary, running server jobs, recent analyses, quick actions.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import SwiftUI11import VQuantKit12import VQuantUI1314/// The research-first home: ask the agent, see what is running and what waits for an answer, then the studies, the15/// markets, the watchlist and the portfolio around it.16struct HomeView: View {17    @Environment(AppModel.self) private var model18    @Environment(\.horizontalSizeClass) private var sizeClass1920    var body: some View {21        ScrollView {22            VStack(alignment: .leading, spacing: 18) {23                OfflineBanner().clipShape(RoundedRectangle(cornerRadius: 10))24                ConflictBanner()25                AskCard()26                ApprovalsCard()27                if sizeClass == .regular {28                    HStack(alignment: .top, spacing: 18) {29                        VStack(spacing: 18) { jobs; studies; recent }30                        VStack(spacing: 18) { markets; watchlist; portfolio }31                    }32                } else {33                    jobs; studies; markets; watchlist; portfolio; recent34                }35            }36            .padding(16)37            .frame(maxWidth: 1180)38            .frame(maxWidth: .infinity)39        }40        .background(Theme.background)41        .navigationTitle(greeting)42        .toolbar {43            ToolbarItem(placement: .topBarTrailing) {44                Button { model.router.showSearch = true } label: { Label("Rechercher partout", systemImage: "magnifyingglass") }45                    .accessibilityIdentifier("quick-search")46            }47            ToolbarItem(placement: .topBarLeading) { RouteLink(.syncStatus) { SyncStatusChip(showsLabel: false).frame(minWidth: 44, minHeight: 44).contentShape(Rectangle()) }.buttonStyle(.plain) }48        }49        .refreshable { await model.next.sync.syncNow(); await model.refreshHome() }50        .onAppear { model.startQuotePolling { model.watchlist.symbols } }51        .onDisappear { model.stopQuotePolling() }52        .accessibilityIdentifier("home")53    }5455    private var greeting: String {56        guard let n = model.account?.name, !n.isEmpty else { return "VQuant" }57        return "Bonjour, \(n)"58    }5960    @ViewBuilder private var jobs: some View {61        let running = model.research.running62        let quant = model.next.lab.running63        if !running.isEmpty || !quant.isEmpty {64            VStack(alignment: .leading, spacing: 10) {65                EditorialHeader("En cours sur le serveur", overline: "Recherche")66                VStack(spacing: 0) {67                    ForEach(running) { g in68                        RouteLink(.run(g.id)) { GenerationRow(generation: g).padding(.vertical, 8) }.buttonStyle(.plain)69                        Divider()70                    }71                    ForEach(quant) { j in72                        RouteLink(.quantJob(j.id)) { LabJobRow(job: j).padding(.vertical, 8) }.buttonStyle(.plain)73                        Divider()74                    }75                }76                Text("Le travail continue sur le serveur, application fermée ou non.").font(.caption).foregroundStyle(Theme.textSecondary)77            }78            .accessibilityElement(children: .contain).accessibilityIdentifier("home-running")79        }80    }8182    @ViewBuilder private var studies: some View {83        let list = model.next.hub.sessions.value?.sessions ?? []84        VStack(alignment: .leading, spacing: 10) {85            EditorialHeader("Études", overline: "Recherche autonome") {86                Button { model.router.section = .research } label: { Text("Tout voir").font(.subheadline).frame(minWidth: 44, minHeight: 44).contentShape(Rectangle()) }87            }88            if list.isEmpty {89                Text(model.next.hub.sessions.isLoading ? "Chargement…" : model.next.hub.sessions.error ?? "Aucune étude pour l’instant. Une étude garde son code, ses données, ses expériences et ses figures sur le serveur : vous la reprenez depuis n’importe quel appareil.")90                    .font(.footnote).foregroundStyle(Theme.textSecondary)91            } else {92                VStack(spacing: 0) {93                    ForEach(list.prefix(4)) { s in94                        RouteLink(.researchSession(s.id)) { StudyRow(session: s).padding(.vertical, 8) }.buttonStyle(.plain)95                        Divider()96                    }97                }98                CachedNotice(at: model.next.hub.sessions.cachedAt)99            }100        }101        .accessibilityElement(children: .contain).accessibilityIdentifier("home-studies")102    }103104    private var markets: some View {105        VStack(alignment: .leading, spacing: 10) {106            let section = model.next.terminal.overview.value?.section("indices")107            EditorialHeader("Marchés", overline: model.next.terminal.overview.value.map { $0.status.isOpen ? "Séance ouverte" : "Séance fermée" }) {108                if let f = section?.freshness { ProvenanceChip(f) }109                else { FreshnessBadge(freshness: model.market.freshness(of: model.market.indices), compact: true) }110            }111            if let items = section?.items, !items.isEmpty {112                LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 10)], spacing: 10) {113                    ForEach(items.prefix(sizeClass == .regular ? 8 : 6)) { item in114                        if let s = item.symbol { RouteLink(.asset(s)) { OverviewTile(item: item) }.buttonStyle(.plain) } else { OverviewTile(item: item) }115                    }116                }117                RouteLink(.terminal) { Label("Ouvrir le terminal : secteurs, taux, devises, calendrier", systemImage: "rectangle.grid.2x2").font(.subheadline).frame(minHeight: 44, alignment: .leading).contentShape(Rectangle()) }118                    .accessibilityIdentifier("home-terminal")119            } else if let list = model.market.indices.value, !list.isEmpty {120                LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 10)], spacing: 10) {121                    ForEach(list.prefix(6)) { q in RouteLink(.asset(q.symbol)) { IndexTile(quote: q) }.buttonStyle(.plain) }122                }123            } else if model.next.terminal.overview.isUnavailable && model.market.indices.isUnavailable {124                StateView(kind: .failed, title: "Marchés indisponibles", message: model.next.terminal.overview.error) { Task { await model.refreshHome() } }125            } else {126                StateView(kind: .loading, title: "Chargement des marchés…")127            }128        }129        .accessibilityElement(children: .contain).accessibilityIdentifier("home-indices")130    }131132    private var watchlist: some View {133        VStack(alignment: .leading, spacing: 10) {134            EditorialHeader(model.watchlist.active?.data.name ?? "Liste de suivi", overline: model.watchlist.active.map { $0.data.name == "Liste de suivi" ? "Synchronisée" : "Liste de suivi" }) {135                if model.watchlist.isPending { Tag(text: "En attente d’envoi", systemImage: "arrow.up.circle", color: Theme.orange) }136            }137            if model.watchlist.symbols.isEmpty {138                Text(model.watchlist.isLoaded || !model.network.isOnline ? "Ajoutez des actifs depuis leur fiche (étoile), la recherche, ou en les glissant ici." : "Chargement…").font(.footnote).foregroundStyle(Theme.textSecondary)139            } else {140                VStack(spacing: 0) {141                    ForEach(model.watchlist.symbols.prefix(8), id: \.self) { s in142                        RouteLink(.asset(s)) {143                            QuoteRow(symbol: s, quote: model.market.quotes[s]?.value, failed: model.market.quoteErrors[s] != nil).padding(.vertical, 8)144                        }145                        .buttonStyle(.plain)146                        .draggableSymbol(s)147                        Divider()148                    }149                }150            }151        }152        .symbolDrop { model.watchlist.add($0, name: nil) }153        .accessibilityElement(children: .contain).accessibilityIdentifier("home-watchlist")154    }155156    @ViewBuilder private var portfolio: some View {157        let lines = PortfolioMath.lines(positions: model.positions, quotes: model.market.quotes.mapValues(\.value))158        VStack(alignment: .leading, spacing: 10) {159            EditorialHeader(model.next.portfolios.selected?.data.name ?? "Portefeuille", overline: "Portefeuille")160            if lines.isEmpty {161                Text("Aucune position enregistrée.").font(.footnote).foregroundStyle(Theme.textSecondary)162                Button { model.router.section = .portfolio } label: { Label("Ajouter une position", systemImage: "plus.circle") }163                    .font(.subheadline).accessibilityIdentifier("quick-position")164            } else {165                let t = PortfolioMath.totals(lines)166                Button { model.router.section = .portfolio } label: {167                    VStack(alignment: .leading, spacing: 4) {168                        Text(Fmt.money(t.value)).font(.mono(.title2, weight: .medium)).privacySensitive()169                        HStack(spacing: 10) {170                            ChangeLabel(percent: t.dayGainPercent.map { $0 * 100 }, absolute: t.dayGain, font: .footnote)171                            Text("aujourd’hui").font(.footnote).foregroundStyle(Theme.textSecondary)172                        }173                        if !t.unpriced.isEmpty { Text("Sans cours : \(t.unpriced.joined(separator: ", "))").font(.caption).foregroundStyle(Theme.warning) }174                    }175                    .frame(maxWidth: .infinity, alignment: .leading)176                }177                .buttonStyle(.plain).accessibilityIdentifier("quick-position")178            }179        }180    }181182    private var recent: some View {183        VStack(alignment: .leading, spacing: 10) {184            EditorialHeader("Analyses récentes", overline: "Historique")185            if let list = model.research.conversations.value, !list.isEmpty {186                VStack(alignment: .leading, spacing: 0) {187                    ForEach(list.prefix(5)) { c in188                        RouteLink(.conversation(c.sessionId)) {189                            VStack(alignment: .leading, spacing: 2) {190                                Text(c.title).font(.subheadline).lineLimit(2).multilineTextAlignment(.leading)191                                Text(Fmt.relative(c.updatedAt)).font(.caption).foregroundStyle(Theme.textSecondary)192                            }193                            .frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 8)194                        }195                        .buttonStyle(.plain)196                        Divider()197                    }198                }199            } else if model.research.conversations.isUnavailable {200                Text("Historique indisponible.").font(.footnote).foregroundStyle(Theme.textSecondary)201            } else if model.research.conversations.isLoading {202                ProgressView()203            } else {204                Text("Aucune analyse pour l’instant.").font(.footnote).foregroundStyle(Theme.textSecondary)205            }206        }207    }208}209210/// The entry point of the app: ask the autonomous research agent. The field opens the composer (question, dataset,211/// budget, model); the chips start it in a given mode.212struct AskCard: View {213    @Environment(AppModel.self) private var model214    var title = "Que voulez-vous étudier ?"215216    var body: some View {217        VStack(alignment: .leading, spacing: 12) {218            HStack(spacing: 8) {219                SparkleMark().frame(width: 22, height: 22)220                Text("Agent de recherche quantitative").font(.caption.weight(.semibold)).tracking(0.9).textCase(.uppercase).foregroundStyle(Theme.textSecondary)221            }222            Text(title).font(.serif(.title, weight: .medium)).fixedSize(horizontal: false, vertical: true)223            Button { model.router.compose(mode: .research) } label: {224                HStack {225                    Text("Posez une question de recherche…").foregroundStyle(Theme.textSecondary)226                    Spacer()227                    Image(systemName: "arrow.up.circle.fill").font(.title2).foregroundStyle(Theme.ember)228                }229                .padding(.horizontal, 14).frame(minHeight: 50)230                .background(Theme.background, in: RoundedRectangle(cornerRadius: 12, style: .continuous))231                .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Theme.border, lineWidth: 1))232            }233            .buttonStyle(.plain)234            .requiresNetwork(model.network.isOnline)235            .accessibilityLabel("Nouvelle recherche")236            .accessibilityIdentifier("ask-field")237            .dropDestination(for: URL.self) { urls, _ in model.router.compose(mode: .research, files: urls.filter(\.isFileURL)); return !urls.isEmpty }238            .symbolDrop { model.router.compose(mode: .research, draft: "Étudie \($0) : ") }239            ScrollView(.horizontal, showsIndicators: false) {240                HStack(spacing: 8) {241                    chip("Analyse rapide", "hare", id: "quick-analysis") { model.router.compose(mode: .fast) }242                    chip("Avec un jeu de données", "tablecells", id: "quick-dataset") { model.router.compose(mode: .research) }243                    chip("Quant Lab", "function", id: "quick-quant") { model.router.open(.quant, compact: UIDevice.current.userInterfaceIdiom == .phone) }244                    chip("Option", "chart.line.uptrend.xyaxis", id: "quick-option") { model.router.open(.quickCalc("option"), compact: UIDevice.current.userInterfaceIdiom == .phone) }245                    chip("VaR", "exclamationmark.shield", id: "quick-var") { model.router.open(.quickCalc("var"), compact: UIDevice.current.userInterfaceIdiom == .phone) }246                }247            }248            Text("Les calculs s’exécutent sur le serveur VQuant ; l’appareil lance, suit, inspecte et reprend.").font(.caption).foregroundStyle(Theme.textSecondary)249        }250        .paperCard(padding: 16, radius: VQTokens.Radius.xl)251        .accessibilityElement(children: .contain).accessibilityIdentifier("ask-card")252    }253254    private func chip(_ title: String, _ image: String, id: String, _ run: @escaping () -> Void) -> some View {255        Button(action: run) {256            Label { Text(title).foregroundStyle(Color.primary) } icon: { Image(systemName: image).foregroundStyle(Theme.orange) }257                .font(.subheadline.weight(.medium))258                .padding(.horizontal, 12).frame(minHeight: 44)259                .overlay(Capsule().strokeBorder(Theme.border, lineWidth: 1))260                .contentShape(Capsule())261        }262        .buttonStyle(.plain).hoverEffect(.highlight).accessibilityIdentifier(id)263    }264}265266/// One item of a market-overview section (index, rate, pair…): what it is, its level in its own unit, its change.267struct OverviewTile: View {268    let item: VQMarketOverview.Item269    var body: some View {270        VStack(alignment: .leading, spacing: 3) {271            Text(item.name).font(.caption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.leading).lineLimit(2, reservesSpace: true)272            Text(Self.level(item)).font(.mono(.callout, weight: .medium))273            ChangeLabel(percent: item.changePct, absolute: item.changePct == nil ? item.change : nil, font: .caption)274        }275        .frame(maxWidth: .infinity, alignment: .leading)276        .padding(10)277        .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10, style: .continuous))278        .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Theme.border, lineWidth: 1))279        .accessibilityElement(children: .combine)280    }281    /// The level in the unit the server states: a yield in percent, a rate with four decimals, a level otherwise.282    static func level(_ i: VQMarketOverview.Item) -> String {283        guard let p = i.price else { return "—" }284        switch i.unit?.known {285        case .yieldPct: return VQFormat.number(p, decimals: 2) + " %"286        case .rate: return VQFormat.number(p, decimals: 4)287        case .pctChange: return VQFormat.number(p, decimals: 2, signed: true) + " %"288        default: return Fmt.price(p)289        }290    }291}292293/// A research workspace in a list.294struct StudyRow: View {295    let session: VQResearchSession296    var body: some View {297        HStack(alignment: .top, spacing: 10) {298            Image(systemName: session.kind == .project ? "books.vertical" : "flask").foregroundStyle(Theme.orange).frame(width: 22)299            VStack(alignment: .leading, spacing: 2) {300                Text(session.title?.isEmpty == false ? session.title! : "Étude sans titre").font(.subheadline.weight(.medium)).lineLimit(2).multilineTextAlignment(.leading)301                Text([session.kind == .project ? "Projet" : "Étude", Fmt.relative(session.updatedAt), session.sessionIds.count > 1 ? "\(session.sessionIds.count) conversations" : nil].compactMap { $0 }.joined(separator: " · "))302                    .font(.caption).foregroundStyle(Theme.textSecondary)303            }304            Spacer(minLength: 0)305        }306        .frame(maxWidth: .infinity, alignment: .leading)307        .contentShape(Rectangle())308        .accessibilityElement(children: .combine)309    }310}311312/// A Quant Lab job in a list (kit model: 19 engines, progress, cancelled status).313struct LabJobRow: View {314    @Environment(AppModel.self) private var model315    let job: VQQuantJob316    var body: some View {317        VStack(alignment: .leading, spacing: 4) {318            HStack {319                Text(model.next.lab.title(job.tool)).font(.subheadline.weight(.medium)).lineLimit(1)320                Spacer(minLength: 8)321                JobStatusBadge.lab(job.status)322            }323            Text(Self.paramSummary(job)).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2)324            if job.isRunning, let p = job.progress { ProgressView(value: min(1, max(0, p))).tint(Theme.orange).accessibilityLabel("Avancement") }325            Text(Fmt.relative(job.startedAt)).font(.caption2).foregroundStyle(Theme.textSecondary)326        }327        .frame(maxWidth: .infinity, alignment: .leading)328        .contentShape(Rectangle())329        .accessibilityElement(children: .combine)330    }331    static func paramSummary(_ job: VQQuantJob) -> String {332        let keys = job.params.keys.sorted { ($0 == "symbol" || $0 == "symbols" ? 0 : 1, $0) < ($1 == "symbol" || $1 == "symbols" ? 0 : 1, $1) }333        return keys.prefix(5).map { k in334            let v = job.params[k]!335            let text = v.displayString ?? v.arrayValue.map { $0.compactMap(\.displayString).joined(separator: ", ") } ?? v.text()336            return "\(k) = \(text.prefix(40))"337        }.joined(separator: " · ")338    }339}340341struct IndexTile: View {342    let quote: Quote343    var body: some View {344        VStack(alignment: .leading, spacing: 3) {345            Text(quote.name ?? quote.symbol).font(.caption).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)346            Text(Fmt.price(quote.price)).font(.callout.weight(.semibold).monospacedDigit())347            ChangeLabel(percent: quote.changePercent, font: .caption)348        }349        .frame(maxWidth: .infinity, alignment: .leading)350        .padding(10)351        .background(Theme.surface2, in: RoundedRectangle(cornerRadius: 10, style: .continuous))352        .accessibilityElement(children: .combine)353    }354}355356struct GenerationRow: View {357    let generation: Generation358    var body: some View {359        VStack(alignment: .leading, spacing: 4) {360            // side by side when it fits, stacked at large text sizes: neither the question nor the status is clipped361            ViewThatFits(in: .horizontal) {362                HStack(alignment: .top) {363                    Text(generation.query).font(.subheadline).lineLimit(2).multilineTextAlignment(.leading)364                    Spacer(minLength: 8)365                    JobStatusBadge.generation(generation.status).fixedSize()366                }367                VStack(alignment: .leading, spacing: 4) {368                    JobStatusBadge.generation(generation.status).fixedSize()369                    Text(generation.query).font(.subheadline).multilineTextAlignment(.leading)370                }371            }372            HStack(spacing: 8) {373                Text(generation.step).lineLimit(1)374                if generation.tools > 0 { Text("· \(generation.tools) outils") }375                Text("· \(Fmt.relative(generation.startedAt))")376            }377            .font(.caption).foregroundStyle(Theme.textSecondary)378            if let e = generation.error { Text(e).font(.caption).foregroundStyle(Theme.down).lineLimit(2) }379        }380        .frame(maxWidth: .infinity, alignment: .leading)381        .contentShape(Rectangle())382        .accessibilityElement(children: .combine)383    }384}385386struct QuantJobRow: View {387    let job: QuantJob388    var title: String?389    var body: some View {390        VStack(alignment: .leading, spacing: 4) {391            HStack {392                Text(title ?? Fmt.label(job.tool)).font(.subheadline.weight(.medium))393                Spacer(minLength: 8)394                JobStatusBadge.quant(job.status)395            }396            Text(QuantJobRow.paramSummary(job)).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2)397            Text(Fmt.relative(job.started)).font(.caption2).foregroundStyle(Theme.textSecondary)398        }399        .frame(maxWidth: .infinity, alignment: .leading)400        .contentShape(Rectangle())401        .accessibilityElement(children: .combine)402    }403    static func paramSummary(_ job: QuantJob) -> String {404        job.params.keys.sorted { ($0 == "symbol" || $0 == "symbols" ? 0 : 1, $0) < ($1 == "symbol" || $1 == "symbols" ? 0 : 1, $1) }405            .map { "\($0) = \(QuantResult.format(job.params[$0]!))" }.joined(separator: " · ")406    }407}408
Files main
Menu

Theme