SPB Git

Repository Public

MarketsOrdersView.swift 28.5 KB 435 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/DeFi/MarketsOrdersView.swift10// Description      : The unified orders and positions of the wallet — whatever11//                    placed them (the app, an API key, an agent), PAPER and12//                    LIVE kept visually distinct and never summed. States are13//                    the server's state machine, shown as served: only FILLED14//                    is a success, UNKNOWN is neither done nor failed. From15//                    here: read, ask for a cancel, close or reduce a position.16//                    Order ENTRY is not here (one order form: the terminal of17//                    Contrats à terme); a live order that waits for the owner's18//                    approval is handed over to that section, never approved19//                    from this screen.20// Module           : Features21// Repository       : https://git.spboucher.ai/sp-wallet-ios22// Created          : 2026-11-1823// Last Modified    : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author           : Simon-Pierre Boucher30// Position         : Professor of Finance31// Institution      : Université du Québec en Outaouais (UQO)32// Department       : Département des sciences administratives33// Organization     : SP Boucher34//35// Website          : https://spboucher.ai36// Git              : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General          : info@spboucher.ai43// Professional     : contact@spboucher.ai44// Direct           : simon@spboucher.ai45// Research         : research@spboucher.ai46// Development      : dev@spboucher.ai47// Support          : support@spboucher.ai48// Security/Admin   : admin@spboucher.ai49// Notifications    : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification   : Public76// Distribution     : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License          : None specified (no license file in this repository)90// Maintainer       : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI98import SPWalletCore99100enum OrderStateFilter: Hashable {101    case all, open, final, state(OrderState)102    func matches(_ o: UnifiedOrder) -> Bool {103        switch self { case .all: true; case .open: o.isOpen; case .final: o.isFinal; case .state(let s): o.status == s }104    }105    var label: String {106        switch self { case .all: String(localized: "Tous les états"); case .open: String(localized: "En cours"); case .final: String(localized: "Terminés"); case .state(let s): s.rawValue }107    }108}109110struct OrdersFilter: Equatable {111    /** nil: both modes, shown in two separate groups */112    var mode: String?113    var venue: String?114    var state: OrderStateFilter = .all115    func apply(_ orders: [UnifiedOrder]) -> [UnifiedOrder] { orders.filter { (mode == nil || $0.mode == mode) && (venue == nil || $0.venue == venue) && state.matches($0) } }116}117118@MainActor @Observable119final class MarketsOrdersModel {120    var orders = Loaded<OrderPage>()121    var positions = Loaded<PositionList>()122    var filter = OrdersFilter()123    var busy = false124    var error: Error?125    var notice: String?126    /** the answer of a close / reduce: the order it created, to be read — it is not an execution */127    var placed: PlacedOrder?128    /** one Idempotency-Key per distinct action: a retry after a lost answer repeats the SAME key */129    private var keys: [String: String] = [:]130    private func key(_ action: String) -> String { if let k = keys[action] { return k }; let k = APIClient.newIdempotencyKey(); keys[action] = k; return k }131132    func load(_ app: AppModel) async {133        orders = await SnapshotRead.read(OrderPage.self, path: "/trading/orders", query: ["limit": "200"], key: "markets-orders", app: app, current: orders)134        positions = await SnapshotRead.read(PositionList.self, path: "/trading/positions", key: "markets-positions", app: app, current: positions)135    }136137    func cancel(_ o: UnifiedOrder, app: AppModel) async {138        guard !busy else { return }139        busy = true; error = nil; notice = nil; defer { busy = false }140        let action = "cancel-\(o.id)"141        do {142            let r = try await OrdersAPI(app.env.client).cancel(orderId: o.id, idempotencyKey: key(action))143            keys[action] = nil144            notice = !r.changed ? String(localized: "L’ordre était déjà terminé : \(OrderWords.label(r.order.status)).")145                : r.order.status == .cancelled ? String(localized: "Annulé (confirmé par le serveur).")146                : r.sent ? String(localized: "Demande d’annulation envoyée à la plateforme. L’ordre n’est annulé que lorsque son état le dit : \(OrderWords.label(r.order.status)).")147                : String(localized: "État renvoyé par le serveur : \(OrderWords.label(r.order.status)).")148        } catch { self.error = error }149        await load(app)150    }151152    func close(_ p: UnifiedPosition, fraction: String?, app: AppModel) async {153        guard !busy else { return }154        busy = true; error = nil; notice = nil; placed = nil; defer { busy = false }155        let action = "close-\(p.id)-\(fraction ?? "all")"156        let api = OrdersAPI(app.env.client)157        do {158            if let fraction { placed = try await api.reducePosition(id: p.id, fraction: fraction, idempotencyKey: key(action)) }159            else { placed = try await api.closePosition(id: p.id, idempotencyKey: key(action)) }160            keys[action] = nil161        } catch { self.error = error }162        await load(app)163    }164}165166struct MarketsOrdersView: View {167    @Environment(AppModel.self) private var model168    @Environment(Router.self) private var router169    @State private var book = MarketsOrdersModel()170    @State private var cancelling: UnifiedOrder?171    @State private var closing: UnifiedPosition?172    @State private var reducing: UnifiedPosition?173    @State private var fraction = ""174175    var body: some View {176        ScrollView {177            LazyVStack(alignment: .leading, spacing: 12) {178                FreshnessBanner()179                Text(String(localized: "Lecture, annulation, fermeture et réduction. La saisie d’un nouvel ordre se fait dans Contrats à terme (ou Échanger pour le comptant)."))180                    .font(.spFootnote).foregroundStyle(Theme.mute)181                filters182                if let n = book.notice { Notice(tone: .info, title: n).accessibilityIdentifier("orders.notice") }183                if let e = book.error { refusal(e) }184                if let p = book.placed { placedCard(p) }185                positionsSection186                ordersSection187            }188            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)189            .frame(maxWidth: 900).frame(maxWidth: .infinity)190        }191        .task { await book.load(model) }192        .refreshable { await book.load(model) }193        .confirmationDialog(String(localized: "Demander l’annulation de cet ordre ?"), isPresented: Binding(get: { cancelling != nil }, set: { if !$0 { cancelling = nil } }), titleVisibility: .visible) {194            Button(String(localized: "Demander l’annulation"), role: .destructive) { if let o = cancelling { Task { await book.cancel(o, app: model) } }; cancelling = nil }195            Button(String(localized: "Garder l’ordre"), role: .cancel) { cancelling = nil }196        }197        .confirmationDialog(String(localized: "Fermer cette position ?"), isPresented: Binding(get: { closing != nil }, set: { if !$0 { closing = nil } }), titleVisibility: .visible) {198            Button(String(localized: "Fermer toute la position (ordre au marché, réduction seule)"), role: .destructive) { if let p = closing { Task { await book.close(p, fraction: nil, app: model) } }; closing = nil }199            Button(String(localized: "Ne pas fermer"), role: .cancel) { closing = nil }200        } message: { Text(closing.map { p in p.mode == "live" ? String(localized: "Position RÉELLE. L’ordre de fermeture attendra ton approbation par clé d’accès dans Contrats à terme.") : String(localized: "Position PAPIER (simulation).") } ?? "") }201        .alert(String(localized: "Réduire la position"), isPresented: Binding(get: { reducing != nil }, set: { if !$0 { reducing = nil; fraction = "" } })) {202            TextField(String(localized: "Fraction, ex. 0,25"), text: $fraction).keyboardType(.decimalPad)203            Button(String(localized: "Réduire")) {204                if let p = reducing, let f = RiskInput.positiveDecimal(fraction), (Double(f) ?? 2) <= 1 { Task { await book.close(p, fraction: f, app: model) } }205                else { book.error = APIError(status: 0, code: "invalid_order", message: String(localized: "La fraction doit être un nombre supérieur à 0 et au plus égal à 1.")) }206                reducing = nil; fraction = ""207            }208            Button(String(localized: "Annuler"), role: .cancel) { reducing = nil; fraction = "" }209        } message: { Text(String(localized: "Part de la position à fermer, entre 0 et 1 (1 = toute la position). Aucune valeur n’est proposée.")) }210    }211212    // MARK: filters213214    private var filters: some View {215        let venues = Array(Set((book.orders.value?.orders ?? []).map(\.venue) + (book.positions.value?.positions ?? []).map(\.venue))).sorted()216        return VStack(alignment: .leading, spacing: 8) {217            Picker(String(localized: "Mode"), selection: Binding(get: { book.filter.mode ?? "" }, set: { book.filter.mode = $0.isEmpty ? nil : $0 })) {218                Text(String(localized: "Les deux")).tag(""); Text(String(localized: "PAPIER")).tag("paper"); Text(String(localized: "RÉEL")).tag("live")219            }.pickerStyle(.segmented).accessibilityIdentifier("orders.mode")220            HStack(spacing: 8) {221                Menu {222                    Button(String(localized: "Toutes les plateformes")) { book.filter.venue = nil }223                    ForEach(venues, id: \.self) { v in Button(v) { book.filter.venue = v } }224                } label: { chip(book.filter.venue ?? String(localized: "Toutes les plateformes"), "building.columns") }225                Menu {226                    ForEach([OrderStateFilter.all, .open, .final], id: \.self) { f in Button(f.label) { book.filter.state = f } }227                    Divider()228                    ForEach(OrderState.all, id: \.self) { s in Button(s.rawValue + " — " + OrderWords.label(s)) { book.filter.state = .state(s) } }229                } label: { chip(book.filter.state.label, "line.3.horizontal.decrease.circle") }230                .accessibilityIdentifier("orders.state")231            }232        }233    }234    private func chip(_ text: String, _ icon: String) -> some View {235        Label(text, systemImage: icon).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.ink).padding(.horizontal, 12).frame(minHeight: 36).background(Theme.elev, in: Capsule())236    }237238    // MARK: refusal and placed order239240    @ViewBuilder private func refusal(_ e: Error) -> some View {241        ErrorNotice(error: e).accessibilityIdentifier("orders.error")242        if let a = e as? APIError, let r = ExecutionRefusal(a) {243            VStack(alignment: .leading, spacing: 0) {244                Text(String(localized: "Détail du refus, tel que servi")).spEyebrow().padding(.bottom, 4)245                FieldRow(label: String(localized: "Code"), value: r.code, mono: true)246                ForEach(r.checks, id: \.self) { c in Divider(); FieldRow(label: c.id, value: String(localized: "observé : \(c.observed ?? "—") · seuil : \(c.limit ?? "—")") + "\n" + c.detail, mono: true) }247                if !r.reasons.isEmpty { Divider(); FieldRow(label: String(localized: "Motifs du mandat"), value: r.reasons.joined(separator: ", "), mono: true) }248            }.spCard(padding: 16)249        }250    }251252    private func placedCard(_ p: PlacedOrder) -> some View {253        VStack(alignment: .leading, spacing: 8) {254            HStack {255                Text(String(localized: "Ordre créé par ta demande")).font(.spHeadline)256                Spacer()257                Pill(text: RiskWords.mode(p.order.mode), tone: RiskWords.modeTone(p.order.mode), icon: RiskWords.modeIcon(p.order.mode))258            }259            Label(OrderWords.label(p.order.status), systemImage: OrderWords.icon(p.order.status)).font(.spCallout.weight(.semibold)).foregroundStyle(OrderWords.tone(p.order.status).color)260                .accessibilityIdentifier("orders.placed.state")261            Text(String(localized: "Ce n’est pas une exécution : lis l’état de l’ordre. Seul « Exécuté » est un succès.")).font(.spFootnote).foregroundStyle(Theme.mute)262            if p.order.status.awaitsOwner {263                Notice(tone: .warn, title: String(localized: "En attente de ton approbation par clé d’accès"),264                       message: String(localized: "Rien n’est signé. L’approbation se fait dans le parcours de la plateforme, section Contrats à terme") + (p.approval?.accountId.map { " (\($0))" } ?? "") + ".")265                Button { router.go(.futures) } label: { Label(String(localized: "Ouvrir Contrats à terme pour approuver"), systemImage: AppSection.futures.icon) }266                    .buttonStyle(.spPrimary).accessibilityIdentifier("orders.placed.goFutures")267            }268        }.spCard()269    }270271    // MARK: positions272273    @ViewBuilder private var positionsSection: some View {274        SectionHeader(title: String(localized: "Positions"))275        if let l = book.positions.value {276            if !book.positions.live { RiskSnapshotNotice(savedAt: book.positions.savedAt, error: book.positions.error) }277            if !l.errors.isEmpty { Notice(tone: .warn, title: String(localized: "Liste partielle : des sources sont illisibles"), message: l.errors.map { "\($0.source) : \($0.message)" }.joined(separator: " · ")) }278            let ps = l.positions.filter { (book.filter.mode == nil || $0.mode == book.filter.mode) && (book.filter.venue == nil || $0.venue == book.filter.venue) }279            if ps.isEmpty { Text(String(localized: "Aucune position pour ce filtre.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("positions.empty") }280            ForEach(ps) { p in positionCard(p) }281        } else if let e = book.positions.error { ErrorNotice(error: e) { Task { await book.load(model) } } }282        else if !model.offlineBrowsing { ProgressView().frame(maxWidth: .infinity) }283    }284285    private func positionCard(_ p: UnifiedPosition) -> some View {286        VStack(alignment: .leading, spacing: 0) {287            HStack {288                Text((p.instrument ?? p.venue) + " · " + OrderWords.side(p.side)).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)289                Spacer()290                Pill(text: RiskWords.mode(p.mode), tone: RiskWords.modeTone(p.mode), icon: RiskWords.modeIcon(p.mode))291            }.padding(.bottom, 4)292            FieldRow(label: String(localized: "Taille · prix d’entrée · prix de marque"), value: "\(Money.exact(p.size)) · \(Money.exact(p.entryPrice)) · \(p.markPrice.map { Money.exact($0) } ?? String(localized: "indisponible"))"); Divider()293            FieldRow(label: String(localized: "Résultat latent") + (p.mode == "paper" ? " (" + String(localized: "PAPIER") + ")" : ""), value: p.unrealizedPnl.map { Money.exact($0) + " USD" } ?? String(localized: "indisponible")); Divider()294            FieldRow(label: String(localized: "Compte · source"), value: p.accountId + (p.source.map { " · \($0)" } ?? ""), mono: true)295            HStack(spacing: 8) {296                Button(String(localized: "Réduire…")) { reducing = p }.buttonStyle(.bordered).accessibilityIdentifier("position.reduce")297                Button(String(localized: "Fermer…"), role: .destructive) { closing = p }.buttonStyle(.bordered).accessibilityIdentifier("position.close")298            }.font(.spCallout.weight(.semibold)).padding(.top, 8).disabled(!model.canOperate || !book.positions.live || book.busy)299        }.spCard()300    }301302    // MARK: orders303304    @ViewBuilder private var ordersSection: some View {305        SectionHeader(title: String(localized: "Ordres"))306        if let page = book.orders.value {307            if !book.orders.live { RiskSnapshotNotice(savedAt: book.orders.savedAt, error: book.orders.error) }308            let shown = book.filter.apply(page.orders)309            if shown.isEmpty { Text(page.orders.isEmpty ? String(localized: "Aucun ordre.") : String(localized: "Aucun ordre pour ce filtre.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("orders.empty") }310            // PAPER and LIVE are never mixed in one list311            ForEach(["live", "paper"], id: \.self) { mode in312                let group = shown.filter { $0.mode == mode }313                if !group.isEmpty {314                    HStack { Pill(text: RiskWords.mode(mode), tone: RiskWords.modeTone(mode), icon: RiskWords.modeIcon(mode)); Text(String(localized: "\(group.count) ordre(s)")).font(.spFootnote).foregroundStyle(Theme.mute) }315                    ForEach(group) { o in orderRow(o) }316                }317            }318            let other = shown.filter { $0.mode != "live" && $0.mode != "paper" }319            ForEach(other) { o in orderRow(o) }320            if page.nextCursor != nil { Text(String(localized: "Les \(page.orders.count) ordres les plus récents sont affichés ; il en existe de plus anciens.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }321        } else if let e = book.orders.error { ErrorNotice(error: e) { Task { await book.load(model) } }.accessibilityIdentifier("orders.loadError") }322        else if model.offlineBrowsing { Text(String(localized: "Aucun instantané des ordres sur cet appareil.")).font(.spCallout).foregroundStyle(Theme.mute) }323        else { ProgressView().frame(maxWidth: .infinity) }324    }325326    private func orderRow(_ o: UnifiedOrder) -> some View {327        VStack(alignment: .leading, spacing: 8) {328            NavigationLink { MarketsOrderDetailView(order: o).wallet(model) } label: {329                VStack(alignment: .leading, spacing: 5) {330                    HStack(alignment: .top) {331                        Text([o.instrument ?? o.venue, OrderWords.side(o.side), o.type].joined(separator: " · ")).font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.ink).multilineTextAlignment(.leading)332                        Spacer()333                        Pill(text: RiskWords.mode(o.mode), tone: RiskWords.modeTone(o.mode), icon: RiskWords.modeIcon(o.mode))334                    }335                    Label(OrderWords.label(o.status) + " (\(o.status.rawValue))", systemImage: OrderWords.icon(o.status)).font(.system(size: 12.5, weight: .semibold)).foregroundStyle(OrderWords.tone(o.status).color)336                    Text([o.size.map { String(localized: "taille \(Money.brief($0))") }, o.price.map { String(localized: "prix \(Money.brief($0))") }, o.filled.map { String(localized: "exécuté \(Money.brief($0))") },337                          o.principal.map { $0.label }, o.created.formatted(date: .abbreviated, time: .shortened)].compactMap { $0 }.joined(separator: " · "))338                        .font(.spFootnote).foregroundStyle(Theme.mute).multilineTextAlignment(.leading)339                }.contentShape(Rectangle())340            }.buttonStyle(.plain).accessibilityIdentifier("order.row")341            if OrderWords.canAskCancel(o) {342                HStack(spacing: 8) {343                    Button(String(localized: "Demander l’annulation"), role: .destructive) { cancelling = o }.buttonStyle(.bordered).font(.spCallout.weight(.semibold))344                        .disabled(!model.canOperate || !book.orders.live || book.busy).accessibilityIdentifier("order.cancel")345                    if o.status.awaitsOwner { Button(String(localized: "Approuver dans Contrats à terme")) { router.go(.futures) }.buttonStyle(.bordered).font(.spCallout.weight(.semibold)).accessibilityIdentifier("order.goFutures") }346                }347            }348        }.spCard(padding: 14)349    }350}351352/** One order: its fields, why it is in its state, its transitions, its fills, and the risk engine's decisions about it. */353struct MarketsOrderDetailView: View {354    @Environment(AppModel.self) private var model355    let order: UnifiedOrder356    @State private var detail: OrderDetail?357    @State private var decisions: [RiskDecision] = []358    @State private var error: Error?359360    var body: some View {361        let o = detail?.order ?? order362        ScrollView {363            VStack(alignment: .leading, spacing: Theme.Space.section) {364                HStack {365                    Pill(text: RiskWords.mode(o.mode), tone: RiskWords.modeTone(o.mode), icon: RiskWords.modeIcon(o.mode))366                    Spacer()367                }368                VStack(alignment: .leading, spacing: 6) {369                    Label(OrderWords.label(o.status), systemImage: OrderWords.icon(o.status)).font(.spHeadline).foregroundStyle(OrderWords.tone(o.status).color).accessibilityIdentifier("order.state")370                    Text(o.status.rawValue + (o.engineStatus.map { " · " + String(localized: "moteur : \($0)") } ?? "")).font(.spMono).foregroundStyle(Theme.mute)371                    if let x = OrderWords.explanation(o) { Text(x).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }372                    if let r = o.reason { Text(r + (o.reasonCode.map { " (\($0))" } ?? "") + (o.rejectCode.map { " · \($0)" } ?? "")).font(.spCallout).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true) }373                }.spCard()374                if detail == nil, let error { ErrorNotice(error: error) { Task { await load() } } }375                if detail == nil, model.offlineBrowsing { Notice(tone: .warn, title: String(localized: "Ligne de l’instantané"), message: String(localized: "L’historique et les exécutions exigent le serveur.")) }376                VStack(alignment: .leading, spacing: 0) {377                    FieldRow(label: String(localized: "Marché"), value: o.instrument ?? "—", mono: true); Divider()378                    FieldRow(label: String(localized: "Plateforme · réseau"), value: "\(o.venue) · \(o.network)"); Divider()379                    FieldRow(label: String(localized: "Sens · type · durée"), value: [OrderWords.side(o.side), o.type, o.tif, o.reduceOnly == true ? String(localized: "réduction seule") : nil].compactMap { $0 }.joined(separator: " · ")); Divider()380                    FieldRow(label: String(localized: "Taille · prix · déclenchement"), value: [o.size, o.price, o.triggerPrice].map { $0.map { Money.exact($0) } ?? "—" }.joined(separator: " · ")); Divider()381                    FieldRow(label: String(localized: "Exécuté · prix moyen"), value: (o.filled.map { Money.exact($0) } ?? "—") + " · " + (o.avgFillPrice.map { Money.exact($0) } ?? "—")); Divider()382                    if let n = o.notionalUsd { FieldRow(label: String(localized: "Notionnel"), value: Fmt.usd(n)); Divider() }383                    FieldRow(label: String(localized: "Placé par"), value: [o.principal?.label, o.origin, o.mandateId.map { String(localized: "mandat \($0)") }].compactMap { $0 }.joined(separator: " · "), mono: true); Divider()384                    FieldRow(label: String(localized: "Créé · mis à jour"), value: o.created.formatted(date: .abbreviated, time: .standard) + " · " + o.updated.formatted(date: .abbreviated, time: .standard)); Divider()385                    FieldRow(label: String(localized: "Identifiant"), value: o.id, mono: true, copyable: true)386                    if let h = o.hash { Divider(); FieldRow(label: String(localized: "Empreinte de l’ordre canonique"), value: h, mono: true, copyable: true) }387                    if let v = o.venueOrderId { Divider(); FieldRow(label: String(localized: "Identifiant à la plateforme"), value: v, mono: true, copyable: true) }388                }.spCard(padding: 16)389                if !decisions.isEmpty {390                    VStack(alignment: .leading, spacing: 0) {391                        SectionHeader(title: String(localized: "Décisions du moteur de risque")).padding(.bottom, 4)392                        ForEach(decisions) { d in RiskDecisionRow(decision: d); if d.id != decisions.last?.id { Divider() } }393                    }.spCard().accessibilityIdentifier("order.decisions")394                }395                if let h = detail?.history, !h.isEmpty {396                    VStack(alignment: .leading, spacing: 0) {397                        SectionHeader(title: String(localized: "Transitions")).padding(.bottom, 4)398                        ForEach(h, id: \.seq) { t in399                            FieldRow(label: "\(t.seq) · " + (Fmt.date(ms: t.at) ?? "") + " · \(t.event)", value: "\(t.from.rawValue) → \(t.to.rawValue) · \(t.reason)" + (t.detail.map { "\n\($0)" } ?? ""), mono: true)400                            if t.seq != h.last?.seq { Divider() }401                        }402                    }.spCard(padding: 16).accessibilityIdentifier("order.history")403                }404                if let f = detail?.fills, !f.isEmpty {405                    VStack(alignment: .leading, spacing: 0) {406                        SectionHeader(title: String(localized: "Exécutions")).padding(.bottom, 4)407                        ForEach(f) { x in408                            FieldRow(label: Fmt.date(ms: x.ts) ?? "", value: String(localized: "\(Money.exact(x.size)) à \(Money.exact(x.price))") + (x.fee.map { " · " + String(localized: "frais \($0) \(x.feeAsset ?? "")") } ?? "") + (x.liquidation == true ? " · " + String(localized: "LIQUIDATION") : ""))409                            if x.id != f.last?.id { Divider() }410                        }411                    }.spCard(padding: 16)412                }413                if let c = o.canonical ?? o.execution ?? o.spot, !c.isNull {414                    DisclosureGroup(String(localized: "Détail brut, tel que servi")) { JSONFields(value: c) }.font(.spCallout.weight(.semibold)).spCard()415                }416            }417            .padding(.horizontal, Theme.Space.gutter).padding(.bottom, 28)418            .frame(maxWidth: 900).frame(maxWidth: .infinity)419        }420        .spPage()421        .navigationTitle(String(localized: "Ordre")).navigationBarTitleDisplayMode(.inline)422        .task { await load() }423        .refreshable { await load() }424    }425426    private func load() async {427        guard !model.offlineBrowsing else { return }428        do { detail = try await OrdersAPI(model.env.client).order(order.id); error = nil } catch let e { error = e }429        if let all = try? await RiskAPI(model.env.client).decisions(limit: 200) {430            let ids = Set([order.id, order.orderId, order.clientOrderId].compactMap { $0 })431            decisions = all.filter { d in [d.orderId, d.clientOrderId].compactMap { $0 }.contains(where: ids.contains) }432        }433    }434}435
Files main
Menu

Theme