Repository Public
1//2// VQuant iOS3// File: VQuant/Features/Portfolio/PortfolioView.swift4// Description: Portfolio: the positions recorded in VQuant, valued with live quotes; allocation, performance of the5// current holdings, drawdown, correlations; position editing with explicit confirmation.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI12import VQuantKit13import VQuantUI1415/// One synced portfolio: valuation with the quotes of the data layer, descriptive analytics on the device, analysis16/// and rebalancing proposals by the server's Portfolio Lab and Risk Lab. `main` is the portfolio the agent reasons about.17struct PortfolioView: View {18 let portfolioId: String19 @Environment(AppModel.self) private var model20 @Environment(\.horizontalSizeClass) private var sizeClass21 @State private var editing: PositionDraft?22 @State private var error: String?23 @State private var pendingDelete: Position?24 @State private var history: [String: [Bar]] = [:]25 @State private var historyError: String?26 @State private var historyLoading = false27 @State private var sort: [KeyPathComparator<PortfolioMath.Line>] = [KeyPathComparator(\.symbol)]28 @State private var objective = "min_variance"29 @State private var launching = false30 @State private var showCreate = false31 @State private var newName = ""3233 private var object: VQObject<VQPortfolio>? { model.next.sync.portfolios[portfolioId] }34 private var positions: [Position] { PortfolioStore.positions(of: object?.data) }35 private var lines: [PortfolioMath.Line] { PortfolioMath.lines(positions: positions, quotes: model.market.quotes.mapValues(\.value)) }36 private var isMain: Bool { portfolioId == VQObjectID.mainPortfolio }3738 var body: some View {39 ScrollView {40 VStack(alignment: .leading, spacing: 16) {41 OfflineBanner().clipShape(RoundedRectangle(cornerRadius: 10))42 identity43 if positions.isEmpty { emptyState } else {44 if sizeClass == .regular {45 HStack(alignment: .top, spacing: 16) { summary; allocation.frame(width: 340) }46 holdingsTable47 } else { summary; allocation; holdingsList }48 analytics49 }50 Text("VQuant n’est relié à aucun courtier : les positions sont déclaratives et aucun ordre ne peut être passé depuis l’application.")51 .font(.caption).foregroundStyle(Theme.textSecondary)52 }53 .padding(16)54 }55 .background(Theme.background)56 .navigationTitle(object?.data.name.isEmpty == false ? object!.data.name : (isMain ? "Portefeuille principal" : "Portefeuille"))57 .toolbar {58 ToolbarItem(placement: .primaryAction) {59 Button { editing = PositionDraft() } label: { Label("Ajouter une position", systemImage: "plus") }60 .accessibilityIdentifier("position-add")61 }62 if sizeClass == .compact {63 ToolbarItem(placement: .topBarLeading) {64 Menu {65 Picker("Portefeuille", selection: Bindable(model.next.portfolios).selectedId) {66 ForEach(model.next.portfolios.all) { p in Text(p.data.name.isEmpty ? p.id : p.data.name).tag(p.id) }67 }68 Button { newName = ""; showCreate = true } label: { Label("Nouveau portefeuille", systemImage: "plus") }69 RouteLink(.portfolios) { Label("Gérer les portefeuilles", systemImage: "list.bullet") }70 } label: { Label("Portefeuilles", systemImage: "briefcase") }71 .accessibilityIdentifier("portfolio-menu")72 }73 }74 }75 .alert("Nouveau portefeuille", isPresented: $showCreate) {76 TextField("Nom", text: $newName)77 Button("Créer") { let n = newName.trimmingCharacters(in: .whitespaces); if !n.isEmpty { Task { _ = await model.next.portfolios.create(name: n) } } }78 Button("Annuler", role: .cancel) {}79 } message: { Text("Un portefeuille de plus dans votre compte, synchronisé sur vos appareils. L’agent raisonne sur le portefeuille principal.") }80 .task { await refresh() }81 // the price history follows the set of holdings (a position added or removed reloads it)82 .task(id: positions.map(\.symbol)) { await model.market.refreshQuotes(positions.map(\.symbol)); await loadHistory() }83 .refreshable { await refresh() }84 .onAppear { model.startQuotePolling { positions.map(\.symbol) } }85 .onDisappear { model.stopQuotePolling() }86 .sheet(item: $editing) { draft in PositionEditor(draft: draft) { await save($0) }.environment(model) }87 .confirmationDialog("Retirer \(pendingDelete?.symbol ?? "") du portefeuille ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible) {88 Button("Retirer la position", role: .destructive) {89 if let p = pendingDelete { Task { if let e = await model.next.portfolios.removePosition(in: portfolioId, symbol: p.symbol) { error = e } } }90 }91 } message: { Text("La position est supprimée du compte VQuant, sur tous vos appareils. Aucune vente n’est exécutée.") }92 .errorAlert($error)93 .accessibilityIdentifier("portfolio")94 }9596 private func refresh() async {97 await model.next.sync.syncNow()98 await model.market.refreshQuotes(positions.map(\.symbol))99 model.writeWidgetSnapshot()100 }101102 private func loadHistory() async {103 let symbols = positions.map(\.symbol)104 guard !symbols.isEmpty else { history = [:]; return }105 historyLoading = true; defer { historyLoading = false }106 var out: [String: [Bar]] = [:]; var failed: [String] = []107 for s in symbols {108 if let l = try? await model.market.bars(s, range: .year) { out[s] = l.value } else { failed.append(s) }109 }110 history = out111 historyError = failed.isEmpty ? nil : "Historique indisponible pour : \(failed.joined(separator: ", "))."112 }113114 private func save(_ d: PositionDraft) async -> String? {115 guard let symbol = WatchlistFile.normalise(d.symbol) else { return "Symbole invalide." }116 guard let qty = d.quantityValue, qty != 0 else { return "La quantité doit être un nombre non nul." }117 if !d.costBasis.isEmpty && d.costValue == nil { return "Le prix de revient n’est pas un nombre." }118 // Online, the symbol must be quoted by the server before it is recorded: no position on an unknown ticker.119 // Offline the write is queued as it is; the position shows "sans cours" until a quote exists.120 if model.network.isOnline {121 await model.market.refreshQuotes([symbol])122 guard model.market.quotes[symbol] != nil else { return "Le serveur ne fournit aucune cotation pour « \(symbol) »." }123 }124 return await model.next.portfolios.savePosition(in: portfolioId, symbol: symbol, quantity: qty, costBasis: d.costValue, note: d.note.isEmpty ? nil : d.note)125 }126127 /// What this portfolio is, and whether its last edit has reached the server.128 private var identity: some View {129 HStack(spacing: 8) {130 if isMain { Tag(text: "Portefeuille de l’agent", systemImage: "sparkles", color: Theme.orange) }131 if let o = object { Tag(text: o.data.baseCurrency) }132 if model.next.portfolios.isPending(portfolioId) { Tag(text: "En attente d’envoi", systemImage: "arrow.up.circle", color: Theme.orange).accessibilityIdentifier("portfolio-pending") }133 Spacer(minLength: 0)134 }135 }136137 // MARK: sections138139 private var emptyState: some View {140 Group {141 if !model.next.portfolios.isLoaded { StateView(kind: .loading, title: "Chargement du portefeuille…") }142 else { StateView(kind: .empty, title: "Aucune position", message: "Ajoutez vos positions pour suivre leur valeur ; l’agent en tient compte dans ses analyses.", systemImage: "briefcase") }143 }144 }145146 private var summary: some View {147 let t = PortfolioMath.totals(lines)148 let fresh = positions.compactMap { model.market.quoteFreshness[$0.symbol] }.min { ($0.asOf ?? .distantPast) < ($1.asOf ?? .distantPast) }149 return Card("Valeur", systemImage: "banknote", trailing: fresh.map { AnyView(ProvenanceChip($0)) }) {150 VStack(alignment: .leading, spacing: 6) {151 Text(Fmt.money(t.value)).font(.mono(.largeTitle, weight: .medium)).minimumScaleFactor(0.6).lineLimit(1).privacySensitive()152 .accessibilityIdentifier("portfolio-value")153 HStack(spacing: 14) {154 VStack(alignment: .leading) { Text("Aujourd’hui").font(.caption).foregroundStyle(Theme.textSecondary); ChangeLabel(percent: t.dayGainPercent.map { $0 * 100 }, absolute: t.dayGain, font: .footnote) }155 if t.gain != nil {156 VStack(alignment: .leading) { Text("Plus-value latente").font(.caption).foregroundStyle(Theme.textSecondary); ChangeLabel(percent: t.gainPercent.map { $0 * 100 }, absolute: t.gain, font: .footnote) }157 }158 }159 if !t.unpriced.isEmpty { Label("Sans cours, exclues du total : \(t.unpriced.joined(separator: ", "))", systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.warning) }160 Text("Montants dans la devise de cotation de chaque titre, sans conversion.").font(.caption2).foregroundStyle(Theme.textSecondary)161 }162 }163 }164165 private var allocation: some View {166 Card("Répartition", systemImage: "chart.pie") { AllocationChart(weights: PortfolioMath.weights(lines)).frame(height: 240) }167 }168169 private var holdingsList: some View {170 Card("Positions", systemImage: "list.bullet") {171 VStack(spacing: 0) {172 ForEach(lines) { l in173 RouteLink(.asset(l.symbol)) { HoldingRow(line: l) }.buttonStyle(.plain)174 .contextMenu { rowMenu(l) }175 .accessibilityIdentifier("holding-\(l.symbol)")176 if l.id != lines.last?.id { Divider() }177 }178 }179 }180 }181182 /// iPad: a sortable table with every column.183 private var holdingsTable: some View {184 Card("Positions", systemImage: "tablecells") {185 Table(lines.sorted(using: sort), sortOrder: $sort) {186 TableColumn("Symbole", value: \.symbol) { l in RouteLink(.asset(l.symbol)) { Text(l.symbol).fontWeight(.semibold) } }187 TableColumn("Quantité", value: \.quantity) { Text(Fmt.quantity($0.quantity)).monospacedDigit() }188 TableColumn("Cours") { Text(Fmt.price($0.price)).monospacedDigit() }189 TableColumn("Valeur") { Text(Fmt.money($0.value)).monospacedDigit().privacySensitive() }190 TableColumn("Jour") { ChangeLabel(percent: $0.dayChangePercent, font: .footnote) }191 TableColumn("Revient") { Text(Fmt.price($0.costBasis)).monospacedDigit() }192 TableColumn("Plus-value") { ChangeLabel(percent: $0.gainPercent.map { $0 * 100 }, absolute: $0.gain, font: .footnote) }193 TableColumn("") { l in Menu { rowMenu(l) } label: { Image(systemName: "ellipsis.circle") }.accessibilityLabel("Actions pour \(l.symbol)") }.width(36)194 }195 .frame(minHeight: CGFloat(lines.count) * 44 + 60)196 .scrollDisabled(true)197 }198 }199200 @ViewBuilder private func rowMenu(_ l: PortfolioMath.Line) -> some View {201 if let p = positions.first(where: { $0.symbol == l.symbol }) {202 Button { editing = PositionDraft(position: p) } label: { Label("Modifier", systemImage: "pencil") }203 Button { model.router.compose(mode: .research, draft: "Étudie \(l.symbol) dans le contexte de mon portefeuille : ") } label: { Label("Demander à l’agent", systemImage: "sparkles") }204 Button(role: .destructive) { pendingDelete = p } label: { Label("Retirer", systemImage: "trash") }205 }206 }207208 @ViewBuilder private var analytics: some View {209 let quantities = Dictionary(uniqueKeysWithValues: positions.map { ($0.symbol, $0.quantity) })210 let points = PortfolioMath.history(quantities: quantities, closes: history)211 Card("Valeur des positions actuelles sur 1 an", systemImage: "chart.line.uptrend.xyaxis") {212 if points.count > 5 {213 ValueHistoryChart(points: points).frame(height: 220).privacySensitive()214 let s = Indicators.summary(closes: points.map(\.value))215 VStack(spacing: 6) {216 KeyValueRow(key: "Rendement sur la période", value: Fmt.fraction(s.totalReturn))217 KeyValueRow(key: "Volatilité annualisée", value: Fmt.fraction(s.annualisedVolatility).replacingOccurrences(of: "+", with: ""))218 KeyValueRow(key: "Drawdown maximal", value: Fmt.fraction(s.maxDrawdown))219 }220 Text("Simulation à quantités constantes : ce que vaudraient les positions d’aujourd’hui à chaque date. VQuant n’enregistre pas de transactions, ce n’est donc pas la performance réelle du compte.")221 .font(.caption2).foregroundStyle(Theme.textSecondary)222 } else if historyLoading { ProgressView() }223 else { Text(historyError ?? "Historique commun insuffisant pour tracer la courbe.").font(.footnote).foregroundStyle(Theme.textSecondary) }224 }225 if points.count > 5 { Card("Drawdown", systemImage: "arrow.down.right") { DrawdownChart(bars: points.map { Bar(date: $0.date, open: $0.value, high: $0.value, low: $0.value, close: $0.value) }).frame(height: 160) } }226 let symbols = positions.map(\.symbol)227 if symbols.count >= 2, symbols.allSatisfy({ history[$0] != nil }) {228 Card("Corrélations (rendements quotidiens, 1 an)", systemImage: "square.grid.3x3") {229 CorrelationHeatmap(symbols: symbols, matrix: PortfolioMath.correlationMatrix(symbols: symbols, closes: history)).frame(minHeight: CGFloat(symbols.count) * 38 + 30)230 }231 }232 serverAnalysis(symbols: symbols)233 }234235 /// Analysis by the server engines. The portfolio is sent as it is declared (quantities and cost basis); nothing236 /// here changes it: a rebalancing is a proposal to read, the person edits positions themselves.237 @ViewBuilder private func serverAnalysis(symbols: [String]) -> some View {238 Card("Analyse par les moteurs du serveur", systemImage: "function") {239 VStack(alignment: .leading, spacing: 10) {240 Text("Allocation, contributions au risque, expositions factorielles, frontière efficiente, scénarios : calculés par le Portfolio Lab et le Risk Lab, avec méthodologie et provenance.").font(.footnote).foregroundStyle(Theme.textSecondary)241 Button { launch("portfolio_lab", objective: "none") } label: { Label("Analyser ce portefeuille", systemImage: "chart.pie") }242 .buttonStyle(QuietButtonStyle()).accessibilityIdentifier("portfolio-analyse")243 Button { launchRisk(symbols) } label: { Label("Mesurer le risque (VaR, tests de résistance, drawdowns)", systemImage: "exclamationmark.shield") }244 .buttonStyle(QuietButtonStyle()).accessibilityIdentifier("portfolio-risk")245 Divider()246 Text("Proposition de rééquilibrage").font(.subheadline.weight(.semibold))247 Picker("Objectif", selection: $objective) {248 Text("Variance minimale").tag("min_variance"); Text("Sharpe maximal").tag("max_sharpe"); Text("Parité de risque").tag("risk_parity")249 Text("HRP").tag("hrp"); Text("Diversification maximale").tag("max_diversification"); Text("Poids égaux").tag("equal_weight")250 }251 .accessibilityIdentifier("portfolio-objective")252 Button { launch("portfolio_lab", objective: objective) } label: { Label("Calculer une proposition", systemImage: "arrow.left.arrow.right") }253 .buttonStyle(QuietButtonStyle()).disabled(symbols.count < 2).accessibilityIdentifier("portfolio-rebalance")254 Text("Une proposition seulement : VQuant n’est relié à aucun courtier, aucun ordre n’est passé et vos positions ne sont pas modifiées.").font(.caption).foregroundStyle(Theme.textSecondary)255 Divider()256 Button {257 model.router.compose(mode: .research, draft: "Analyse le risque de mon portefeuille actuel : concentration, VaR, corrélations, scénarios de stress, et propose des ajustements.")258 } label: { Label("Confier l’étude à l’agent de recherche", systemImage: "sparkles") }259 }260 .disabled(launching).requiresNetwork(model.network.isOnline)261 }262 }263264 private func launch(_ tool: String, objective: String) {265 let list: [VQJSON] = positions.map { p in266 var o: VQJSONObject = ["symbol": .string(p.symbol), "quantity": .number(p.quantity)]267 if let c = p.costBasis { o["costBasis"] = .number(c) }268 return .object(o)269 }270 var params: VQJSONObject = ["positions": .array(list), "objective": .string(objective), "base_currency": .string(object?.data.baseCurrency ?? "USD")]271 if let b = object?.data.benchmark, !b.isEmpty { params["benchmark"] = .string(b) }272 start(tool, params)273 }274 private func launchRisk(_ symbols: [String]) {275 let values = symbols.map { s in lines.first { $0.symbol == s }?.value ?? 0 }276 var params: VQJSONObject = ["symbols": VQJSON(symbols)]277 if values.allSatisfy({ $0 != 0 }) { params["weights"] = VQJSON(values) } // rescaled to sum to 1 by the engine278 start("risk_lab", params)279 }280 private func start(_ tool: String, _ params: VQJSONObject) {281 launching = true282 Task {283 defer { launching = false }284 do {285 let job = try await model.next.lab.start(tool: tool, params: params)286 model.router.open(.quantJob(job.id), compact: sizeClass == .compact)287 } catch { self.error = nextMessage(error) }288 }289 }290}291292/// Every portfolio of the account (iPad list column; "Gérer" on the iPhone).293struct PortfoliosListView: View {294 @Environment(AppModel.self) private var model295 @State private var showCreate = false296 @State private var name = ""297 @State private var renaming: VQObject<VQPortfolio>?298 @State private var pendingDelete: VQObject<VQPortfolio>?299300 var body: some View {301 List {302 Section {303 let all = model.next.portfolios.all304 if all.isEmpty { Text(model.next.portfolios.isLoaded ? "Aucun portefeuille. Le portefeuille principal est créé à la première position." : "Chargement…").foregroundStyle(Theme.textSecondary) }305 ForEach(all) { p in306 RouteLink(.portfolio(p.id)) { row(p) }307 .accessibilityIdentifier("portfolio-\(p.id)")308 .swipeActions {309 if p.id != VQObjectID.mainPortfolio { Button("Supprimer", role: .destructive) { pendingDelete = p } }310 Button("Renommer") { name = p.data.name; renaming = p }.tint(.gray)311 }312 }313 } footer: { Text("Les portefeuilles sont déclaratifs et synchronisés sur vos appareils. L’agent raisonne sur le portefeuille principal.").foregroundStyle(Theme.textSecondary) }314 if model.next.portfolios.all.first(where: { $0.id == VQObjectID.mainPortfolio }) == nil {315 Section { RouteLink(.portfolio(VQObjectID.mainPortfolio)) { Label("Portefeuille principal (vide)", systemImage: "sparkles") } }316 }317 }318 .navigationTitle("Portefeuilles")319 .toolbar {320 ToolbarItem(placement: .primaryAction) { Button { name = ""; showCreate = true } label: { Label("Nouveau portefeuille", systemImage: "plus") }.accessibilityIdentifier("portfolio-new") }321 }322 .alert("Nouveau portefeuille", isPresented: $showCreate) {323 TextField("Nom", text: $name)324 Button("Créer") { let n = name.trimmingCharacters(in: .whitespaces); if !n.isEmpty { Task { _ = await model.next.portfolios.create(name: n) } } }325 Button("Annuler", role: .cancel) {}326 }327 .alert("Renommer", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {328 TextField("Nom", text: $name)329 Button("Enregistrer") { if let p = renaming { let n = name; Task { await model.next.portfolios.rename(p.id, to: n) } } }330 Button("Annuler", role: .cancel) {}331 }332 .confirmationDialog("Supprimer « \(pendingDelete?.data.name ?? "") » ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible) {333 Button("Supprimer le portefeuille", role: .destructive) { if let p = pendingDelete { Task { await model.next.portfolios.delete(p.id) } } }334 } message: { Text("Il est effacé du compte, sur tous vos appareils, avec ses versions archivées.") }335 .accessibilityIdentifier("portfolios")336 }337338 private func row(_ p: VQObject<VQPortfolio>) -> some View {339 let lines = PortfolioMath.lines(positions: PortfolioStore.positions(of: p.data), quotes: model.market.quotes.mapValues(\.value))340 let t = PortfolioMath.totals(lines)341 return HStack {342 VStack(alignment: .leading, spacing: 2) {343 HStack(spacing: 6) {344 Text(p.data.name.isEmpty ? p.id : p.data.name).font(.body.weight(.medium))345 if p.id == VQObjectID.mainPortfolio { Image(systemName: "sparkles").font(.caption).foregroundStyle(Theme.orange).accessibilityLabel("Portefeuille de l’agent") }346 }347 Text("\(p.data.positions.count) position\(p.data.positions.count > 1 ? "s" : "") · \(p.data.baseCurrency)").font(.caption).foregroundStyle(Theme.textSecondary)348 }349 Spacer()350 if !lines.isEmpty { Text(Fmt.money(t.value)).font(.mono(.callout)).privacySensitive() }351 }352 .accessibilityElement(children: .combine)353 }354}355356struct HoldingRow: View {357 let line: PortfolioMath.Line358 var body: some View {359 HStack {360 VStack(alignment: .leading, spacing: 2) {361 Text(line.symbol).font(.body.weight(.semibold))362 Text("\(Fmt.quantity(line.quantity)) × \(Fmt.price(line.price))").font(.caption).foregroundStyle(Theme.textSecondary).monospacedDigit()363 }364 Spacer()365 VStack(alignment: .trailing, spacing: 2) {366 Text(Fmt.money(line.value)).font(.body.monospacedDigit()).privacySensitive()367 ChangeLabel(percent: line.gainPercent.map { $0 * 100 } ?? line.dayChangePercent, font: .caption)368 }369 }370 .padding(.vertical, 8).contentShape(Rectangle())371 .accessibilityElement(children: .combine)372 }373}374375struct PositionDraft: Identifiable {376 let id = UUID()377 var symbol = ""378 var quantity = ""379 var costBasis = ""380 var note = ""381 var isNew = true382 init() {}383 init(position p: Position) {384 symbol = p.symbol; quantity = Self.plain(p.quantity); costBasis = p.costBasis.map(Self.plain) ?? ""; note = p.note ?? ""; isNew = false385 }386 static func plain(_ v: Double) -> String { v == v.rounded() && abs(v) < 1e15 ? String(Int64(v)) : String(v) }387 static func number(_ s: String) -> Double? {388 let t = s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: " ", with: "")389 guard let v = Double(t), v.isFinite else { return nil }390 return v391 }392 var quantityValue: Double? { Self.number(quantity) }393 var costValue: Double? { costBasis.isEmpty ? nil : Self.number(costBasis).flatMap { $0 >= 0 ? $0 : nil } }394}395396struct PositionEditor: View {397 @State var draft: PositionDraft398 /// Returns an error message, or nil when the server accepted the position.399 let save: (PositionDraft) async -> String?400 @Environment(\.dismiss) private var dismiss401 @Environment(AppModel.self) private var model402 @State private var saving = false403 @State private var error: String?404 @State private var confirming = false405406 var body: some View {407 NavigationStack {408 Form {409 Section {410 LabeledContent("Symbole") {411 TextField("AAPL", text: $draft.symbol).textInputAutocapitalization(.characters).autocorrectionDisabled().multilineTextAlignment(.trailing)412 .disabled(!draft.isNew).accessibilityIdentifier("position-symbol")413 }414 LabeledContent("Quantité") {415 TextField("0", text: $draft.quantity).keyboardType(.numbersAndPunctuation).multilineTextAlignment(.trailing).accessibilityIdentifier("position-quantity")416 }417 LabeledContent("Prix de revient") {418 TextField("facultatif", text: $draft.costBasis).keyboardType(.numbersAndPunctuation).multilineTextAlignment(.trailing).accessibilityIdentifier("position-cost")419 }420 TextField("Note (facultative)", text: $draft.note, axis: .vertical).lineLimit(1...3)421 } footer: {422 Text("La position est enregistrée dans votre compte VQuant, synchronisée sur vos appareils" + (model.network.isOnline ? "" : " dès le retour de la connexion (hors ligne : elle est mise en file d’attente)") + ". Ce n’est pas un ordre : rien n’est acheté ni vendu.")423 }424 if let error { Section { Label(error, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down).accessibilityIdentifier("position-error") } }425 }426 .navigationTitle(draft.isNew ? "Nouvelle position" : "Modifier \(draft.symbol)").navigationBarTitleDisplayMode(.inline)427 .toolbar {428 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }429 ToolbarItem(placement: .confirmationAction) {430 Button("Enregistrer") { confirming = true }431 .disabled(saving || draft.symbol.isEmpty || draft.quantity.isEmpty)432 .accessibilityIdentifier("position-save")433 }434 }435 .confirmationDialog("Enregistrer \(draft.quantity) × \(draft.symbol.uppercased()) ?", isPresented: $confirming, titleVisibility: .visible) {436 Button("Confirmer") {437 saving = true438 Task {439 // A single request per confirmation: the button is disabled while it is in flight.440 error = await save(draft); saving = false441 if error == nil { Haptics.success(); dismiss() }442 }443 }444 .accessibilityIdentifier("position-confirm")445 } message: { Text("Modifie le portefeuille déclaré dans VQuant.") }446 .overlay { if saving { ProgressView() } }447 }448 .presentationDetents([.medium, .large])449 }450}451