SPB Git

Repository Public

FuturesRiskView.swift 30.1 KB 514 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/Futures/FuturesRiskView.swift10// Description      : The API-side risk engine: the global kill switch and the11//                    read-only switch, the automatic stops, the limits of each12//                    mode (paper / live) with what is missing, the exposure of13//                    each book (paper, live mainnet, live testnet — never14//                    merged), the engine's decision log and the server locks.15//                    The server's rule is kept as it is: what REMOVES authority16//                    is one click and a confirmation, without passkey (engaging17//                    a switch, tightening a limit, switching an automatic stop18//                    on); what GIVES authority back (releasing a switch,19//                    loosening a limit, switching a stop off) is prepared,20//                    verified by the Core against its challenge, reviewed and21//                    approved with the passkey.22// Module           : Features23// Repository       : https://git.spboucher.ai/sp-wallet-macos24// Created          : 2026-11-1825// Last Modified    : 2026-11-1826//27// =============================================================================28// AUTHOR & PROFESSIONAL AFFILIATION29// =============================================================================30//31// Author           : Simon-Pierre Boucher32// Position         : Professor of Finance33// Institution      : Université du Québec en Outaouais (UQO)34// Department       : Département des sciences administratives35// Organization     : SP Boucher36//37// Website          : https://spboucher.ai38// Git              : https://git.spboucher.ai39//40// =============================================================================41// OFFICIAL CONTACT DIRECTORY42// =============================================================================43//44// General          : info@spboucher.ai45// Professional     : contact@spboucher.ai46// Direct           : simon@spboucher.ai47// Research         : research@spboucher.ai48// Development      : dev@spboucher.ai49// Support          : support@spboucher.ai50// Security/Admin   : admin@spboucher.ai51// Notifications    : notifications@spboucher.ai52//53// Preferred Contact: support@spboucher.ai54//55// =============================================================================56// COPYRIGHT & INTELLECTUAL PROPERTY57// =============================================================================58//59// Copyright (c) 202660// Simon-Pierre Boucher61//62// All rights reserved where applicable.63//64// This file is governed by the applicable project license,65// copyright notices, institutional agreements and relevant law.66//67// Unless expressly authorized by the applicable license or68// rights holder, copying, redistribution, sublicensing,69// publication and commercial exploitation are not permitted.70//71// Existing third-party rights and notices remain unaffected.72//73// =============================================================================74// CONFIDENTIALITY & SECURITY75// =============================================================================76//77// Classification   : Public78// Distribution     : Public repository; use is governed by the project license79// Security Contact : admin@spboucher.ai80//81// Access to this source does not independently grant permission82// to redistribute or disclose confidential materials.83//84// Do not embed credentials, private keys, access tokens,85// certificates or confidential personal information.86//87// =============================================================================88// LICENSE & MAINTENANCE89// =============================================================================90//91// License          : None specified (no license file in this repository)92// Maintainer       : Simon-Pierre Boucher93// Technical Contact: dev@spboucher.ai94//95// =============================================================================96// END OF SP BOUCHER SOURCE HEADER97// =============================================================================9899import SwiftUI100import SPWalletCore101102@MainActor @Observable final class FutRiskFlow {103    enum Sheet: Identifiable {104        case release(RiskSwitchReleaseApproval)105        case limits(RiskLimitsApproval)106        case auto(AutoKillApproval)107        var id: String {108            switch self { case .release(let a): "rel-\(a.intent.nonce)"; case .limits(let a): "lim-\(a.intent.nonce)"; case .auto(let a): "auto-\(a.intent.nonce)" }109        }110    }111    let model: AppModel112    let store: FuturesStore113    var sheet: Sheet?114    private(set) var busy = false115    private(set) var approving = false116    var error: String?117    var sheetError: String?118    var notice: String?119120    init(model: AppModel, store: FuturesStore) { self.model = model; self.store = store }121    private var risk: RiskAPI { store.risk }122123    private func run(_ body: () async throws -> Void) async {124        guard model.canOperate, !busy, !approving else { return }125        busy = true; error = nil; notice = nil126        defer { busy = false }127        do { try await body() } catch { self.error = model.describe(error); await store.loadRiskState() }128    }129130    /// One click and a confirmation, no passkey. The switch is shown as engaged only when the server's answer says so.131    func engage(_ kind: RiskSwitchKind, reason: String) async {132        await run {133            let s: RiskSwitches134            if kind == .killSwitch { s = try await risk.engageKillSwitch(reason: reason) } else { s = try await risk.engageReadOnly(reason: reason) }135            await store.loadRiskState()136            notice = (kind == .killSwitch ? "Coupe-circuit" : "Mode lecture seule") + " engagé, confirmé par le serveur" + (s.state(of: kind).engagedAt.map { " à \(Fmt.dateSeconds($0))" } ?? "") + "."137        }138    }139140    func prepareRelease(_ kind: RiskSwitchKind) async {141        guard let displayed = store.riskState.value?.switches.state(of: kind) else { return }142        await run {143            switch try await risk.prepareRelease(kind, displayed: displayed) {144            case .notEngaged: notice = "Ce commutateur n’est pas engagé : rien à lever."; await store.loadRiskState()145            case .approval(let a): sheetError = nil; sheet = .release(a)146            }147        }148    }149150    func setAuto(_ auto: AutoKillSettings) async {151        await run {152            switch try await risk.prepareAutoKill(auto) {153            case .passkeyNotNeeded: _ = try await risk.setAutoKill(auto); await store.loadRiskState(); notice = "Arrêts automatiques mis à jour (aucun n’a été désactivé : pas de passkey requise)."154            case .approval(let a): sheetError = nil; sheet = .auto(a)155            }156        }157    }158159    func saveLimits(mode: RiskMode, limits: EngineRiskLimits) async {160        await run {161            switch try await risk.prepareLimits(mode: mode, limits: limits) {162            case .passkeyNotNeeded: _ = try await risk.setLimits(mode: mode, limits: limits); await store.loadRiskState(); notice = "Limites \(mode == .paper ? "papier" : "réelles") enregistrées (rien n’est assoupli : pas de passkey requise)."163            case .approval(let a): sheetError = nil; sheet = .limits(a)164            }165        }166    }167168    func approve() async {169        guard let sheet, model.canOperate, !approving else { return }170        approving = true; sheetError = nil171        defer { approving = false }172        do {173            switch sheet {174            case .release(let a): _ = try await risk.release(a, with: model.authenticator); notice = (a.kind == .killSwitch ? "Coupe-circuit" : "Mode lecture seule") + " levé par le serveur."175            case .limits(let a): _ = try await risk.approveLimits(a, with: model.authenticator); notice = "Limites assouplies enregistrées par le serveur."176            case .auto(let a): _ = try await risk.approveAutoKill(a, with: model.authenticator); notice = "Arrêts automatiques modifiés par le serveur."177            }178            self.sheet = nil179            await store.loadRiskState()180        } catch PasskeyError.cancelled {181        } catch {182            // the answer may have been lost after the server acted: the state is read again rather than a second signature asked183            sheetError = model.describe(error)184            await store.loadRiskState()185        }186    }187188    func dismiss() { if !approving { sheet = nil; sheetError = nil } }189}190191struct FutRiskView: View {192    let model: AppModel193    @Bindable var store: FuturesStore194    @State private var flow: FutRiskFlow?195196    var body: some View {197        Group {198            if let flow { content(flow) } else { ProgressView() }199        }200        .sheet(item: Binding(get: { flow?.sheet }, set: { if $0 == nil { flow?.dismiss() } })) { s in201            if let flow { FutRiskSheet(model: model, flow: flow, sheet: s) }202        }203        .task { if flow == nil { flow = FutRiskFlow(model: model, store: store) }; await store.loadRiskState() }204    }205206    @ViewBuilder private func content(_ flow: FutRiskFlow) -> some View {207        if let e = store.riskState.error { Banner(.danger, "État du moteur de risque indisponible : \(e)" + (store.riskState.at.map { " — ce qui suit date du \(Fmt.dateSeconds($0))" } ?? "")) }208        if let e = flow.error { Banner(.danger, e) }209        if let n = flow.notice { Banner(.info, n) }210        if let s = store.riskState.value {211            FutSwitchesCard(model: model, flow: flow, state: s)212            FutLocksCard(store: store)213            Card("Arrêt d’urgence du signataire") {214                let h = model.portfolio?.value.halted215                Label(h == true ? "ACTIF : plus rien ne peut être signé" : h == false ? "Inactif" : "État inconnu (signataire injoignable)", systemImage: h == true ? "xmark.shield.fill" : h == false ? "checkmark.shield" : "questionmark.circle")216                    .foregroundStyle(h == true ? Theme.negative : h == false ? Theme.positive : Theme.warning)217                Text("Distinct du coupe-circuit ci-dessus : il s’engage dans l’écran Sécurité et ne se lève que sur la machine du signataire.").font(.caption).foregroundStyle(.secondary)218            }219            FutAutoKillCard(model: model, flow: flow, auto: s.auto)220            HStack(alignment: .top, spacing: 16) {221                FutExposureCard(title: "Exposition — papier", mode: .paper, e: s.exposure.paper)222                FutExposureCard(title: "Exposition — testnet", mode: .testnet, e: s.exposure.liveTestnet)223                FutExposureCard(title: "Exposition — réel", mode: .mainnet, e: s.exposure.live)224            }225            Text("Les trois livres ne sont jamais additionnés.").font(.caption).foregroundStyle(.secondary)226            FutLimitsCard(model: model, flow: flow, view: s.limits.live, color: FutMode.mainnet.color, title: "Limites — ordres réels (mainnet et testnet)")227            FutLimitsCard(model: model, flow: flow, view: s.limits.paper, color: FutMode.paper.color, title: "Limites — ordres papier (simulation)")228            FutDecisionsCard(decisions: s.decisions)229        } else if store.riskState.error == nil {230            ProgressView().frame(maxWidth: .infinity, minHeight: 120)231        }232    }233}234235// MARK: switches236237private struct FutSwitchesCard: View {238    let model: AppModel239    let flow: FutRiskFlow240    let state: RiskState241    @State private var reason = ""242    @State private var confirm: RiskSwitchKind?243244    var body: some View {245        Card("Commutateurs globaux") {246            row(.killSwitch, state.switches.killSwitch, title: "Coupe-circuit (kill switch)", on: "ENGAGÉ : aucun nouvel ordre n’ajoute de risque, sur toutes les plateformes et dans tous les modes. Annulations et ordres strictement réducteurs passent.", off: "Non engagé.")247            Divider()248            row(.readOnly, state.switches.readOnly, title: "Mode lecture seule", on: "ENGAGÉ : seules les annulations passent.", off: "Non engagé.")249            Divider()250            HStack {251                TextField("Raison (facultative, jointe à l’engagement)", text: $reason).textFieldStyle(.roundedBorder).frame(maxWidth: 380)252                if flow.busy { ProgressView().controlSize(.small) }253            }254            Text("Engager est immédiat et ne demande pas de passkey. Lever un commutateur redonne de l’autorité : votre passkey signe la levée de l’engagement exact affiché ici.").font(.caption).foregroundStyle(.secondary)255        }256    }257258    @ViewBuilder private func row(_ kind: RiskSwitchKind, _ s: RiskSwitch, title: String, on: String, off: String) -> some View {259        HStack(alignment: .top, spacing: 12) {260            Image(systemName: s.on ? "power.circle.fill" : "power.circle").font(.title2).foregroundStyle(s.on ? Theme.negative : .secondary)261            VStack(alignment: .leading, spacing: 3) {262                Text(title).font(.headline)263                Text(s.on ? on : off).font(.callout).foregroundStyle(s.on ? Theme.negative : .secondary).fixedSize(horizontal: false, vertical: true)264                if s.on { Text("Depuis \(Fmt.dateSeconds(s.engagedAt)) · par \(s.by?.label ?? "inconnu")" + (s.reason.map { $0.isEmpty ? "" : " · raison : \($0)" } ?? "")).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }265            }266            Spacer()267            if s.on {268                Button("Lever (passkey)…") { Task { await flow.prepareRelease(kind) } }.disabled(!model.canOperate || flow.busy)269            } else {270                Button(kind == .killSwitch ? "Engager le coupe-circuit…" : "Engager la lecture seule…", role: .destructive) { confirm = kind }.disabled(!model.canOperate || flow.busy)271                    .confirmationDialog(kind == .killSwitch ? "Engager le coupe-circuit global ?" : "Engager le mode lecture seule ?", isPresented: Binding(get: { confirm == kind }, set: { if !$0 { confirm = nil } })) {272                        Button("Engager maintenant", role: .destructive) { Task { await flow.engage(kind, reason: reason) } }273                    } message: { Text(kind == .killSwitch ? "Effet immédiat pour tous les modes et toutes les plateformes. Les positions ne sont pas clôturées. Le lever demandera votre passkey." : "Effet immédiat : seules les annulations passeront. Le lever demandera votre passkey.") }274            }275        }276    }277}278279private struct FutAutoKillCard: View {280    let model: AppModel281    let flow: FutRiskFlow282    let auto: AutoKillSettings283    var body: some View {284        Card("Arrêts automatiques") {285            toggle("Perte totale maximale atteinte", \.totalLoss)286            toggle("Baisse maximale depuis le sommet (drawdown) atteinte", \.drawdown)287            toggle("Perte quotidienne maximale atteinte", \.dailyLoss)288            Text("Quand la limite correspondante est franchie, le serveur engage lui-même le coupe-circuit. Activer un arrêt est libre ; en désactiver un exige votre passkey.").font(.caption).foregroundStyle(.secondary)289        }290    }291    private func toggle(_ label: String, _ key: WritableKeyPath<AutoKillSettings, Bool>) -> some View {292        Toggle(label, isOn: Binding(get: { auto[keyPath: key] }, set: { v in var next = auto; next[keyPath: key] = v; Task { await flow.setAuto(next) } }))293            .disabled(!model.canOperate || flow.busy)294    }295}296297// MARK: exposure298299private struct FutExposureCard: View {300    let title: String301    let mode: FutMode302    let e: RiskExposure303    var body: some View {304        Card(title, trailing: AnyView(FutModeBadge(mode: mode))) {305            if let err = e.error { Banner(.warning, "Livre illisible : \(err)") }306            FutStatGrid(minimum: 120) {307                FutStat("Valeur", e.isReadable ? FutNum.usd(e.equity) : nil)308                FutStat("Exposition brute", e.isReadable ? FutNum.usd(e.grossExposure) : nil)309                FutStat("Levier du livre", e.isReadable ? (e.leverage.map { "\(FutNum.exact($0, maxFraction: 2))×" } ?? "—") : nil)310                FutStat("Sommet de valeur", e.isReadable ? FutNum.usd(e.peakEquity) : nil)311            }312            ForEach(e.byAsset ?? [], id: \.asset) { a in313                HStack { Text(a.asset).fontWeight(.medium); Spacer(); Text("long \(FutNum.usd(a.long)) · short \(FutNum.usd(a.short)) · net \(FutNum.usd(a.net))").font(.callout).monospacedDigit().foregroundStyle(.secondary) }314            }315            ForEach(e.positions ?? [], id: \.instrument) { p in316                HStack { FutSideText(side: p.side); Text(p.instrument).font(.callout); Spacer(); Text("\(FutNum.usd(p.notional))" + (p.liquidationDistanceBps.map { " · liq. à \(FutNum.exact($0, maxFraction: 0)) pb" } ?? "")).font(.callout).monospacedDigit().foregroundStyle(.secondary) }317            }318            if let errs = e.errors, !errs.isEmpty { Text("Chiffres PARTIELS — sources illisibles : \(errs.joined(separator: " ; "))").font(.caption).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true) }319            if let t = FutNum.ms(e.ts) { Text("Calculé \(Fmt.relative(t))").font(.caption).foregroundStyle(.secondary) }320        }321    }322}323324// MARK: limits325326private struct FutLimitsCard: View {327    let model: AppModel328    let flow: FutRiskFlow329    let view: RiskLimitsView330    let color: Color331    let title: String332    @State private var editing = false333    @State private var draft: [String: String] = [:]334335    static let decimals: [(String, String, WritableKeyPath<EngineRiskLimits, String?>)] = [336        ("maxOrderNotional", "Notionnel max par ordre ($)", \.maxOrderNotional), ("maxDailyNotional", "Notionnel max par jour ($)", \.maxDailyNotional),337        ("maxOrderLeverage", "Levier max d’un ordre", \.maxOrderLeverage), ("maxAccountLeverage", "Levier max du compte", \.maxAccountLeverage),338        ("maxGrossExposure", "Exposition brute max ($)", \.maxGrossExposure), ("maxNetExposure", "Exposition nette max ($)", \.maxNetExposure),339        ("maxDailyLoss", "Perte quotidienne max ($)", \.maxDailyLoss), ("maxTotalLoss", "Perte totale max ($)", \.maxTotalLoss), ("maxDrawdownBps", "Drawdown max (pb)", \.maxDrawdownBps),340        ("maxVenueCollateralShareBps", "Part max du collatéral par plateforme (pb)", \.maxVenueCollateralShareBps), ("minLiquidationDistanceBps", "Distance min. à la liquidation (pb)", \.minLiquidationDistanceBps),341        ("maxSlippageBps", "Glissement max (pb)", \.maxSlippageBps), ("maxSourceDeviationBps", "Écart max entre sources de prix (pb)", \.maxSourceDeviationBps),342    ]343    static let integers: [(String, String, WritableKeyPath<EngineRiskLimits, Int?>)] = [344        ("maxOrdersPerMinute", "Ordres par minute", \.maxOrdersPerMinute), ("maxOrdersPerHour", "Ordres par heure", \.maxOrdersPerHour), ("maxOrdersPerDay", "Ordres par jour", \.maxOrdersPerDay),345        ("maxBookAgeMs", "Âge max du carnet (ms)", \.maxBookAgeMs), ("minPriceSources", "Sources de prix minimales", \.minPriceSources),346    ]347348    static func lines(_ l: EngineRiskLimits) -> [(String, String)] {349        let o = (try? JSONValue.from(l))?.objectValue ?? [:]350        return EngineRiskLimits.fieldNames.compactMap { k in o[k].flatMap { $0.isNull ? nil : (k, $0.displayText) } }351    }352353    /// The edited set: the stored one with the scalar fields replaced; keyed limits and lists are kept untouched.354    private var edited: EngineRiskLimits? {355        var l = view.stored356        for (k, _, path) in Self.decimals {357            let t = (draft[k] ?? "").trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")358            if t.isEmpty { l[keyPath: path] = nil } else { guard let d = VenueDecimal(t), !d.isNegative else { return nil }; l[keyPath: path] = d.description }359        }360        for (k, _, path) in Self.integers {361            let t = (draft[k] ?? "").trimmingCharacters(in: .whitespaces)362            if t.isEmpty { l[keyPath: path] = nil } else { guard let n = Int(t), n >= 0 else { return nil }; l[keyPath: path] = n }363        }364        return l365    }366367    var body: some View {368        Card(title, trailing: AnyView(Circle().fill(color).frame(width: 10, height: 10).accessibilityHidden(true))) {369            if view.ownerOrdersRefused == true || !view.missing.isEmpty {370                Banner(.warning, "Limites de capital absentes pour vos propres ordres : \(view.missing.joined(separator: ", ")). Tant qu’elles manquent, vos ordres qui ajoutent du risque dans ce mode sont refusés.")371            }372            if let m = view.missingForAutomation, !m.isEmpty { Text("Absentes pour les clés d’API et les agents : \(m.joined(separator: ", "))" + (view.automationOrdersRefused == true ? " — leurs ordres sont refusés." : "")).font(.callout).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true) }373            HStack(alignment: .top, spacing: 20) {374                set("En vigueur pour vos ordres", view.effectiveOwner ?? view.effective)375                set("En vigueur pour clés d’API et agents", view.effective)376                set("Enregistrées par vous", view.stored)377            }378            if let seed = view.seed { Text("Limites reprises de vos autorisations antérieures (\(seed.sources.map { "\($0.field) ← \($0.from)" }.joined(separator: ", ")))" + (seed.notSeeded.isEmpty ? "" : " ; non reprises : \(seed.notSeeded.joined(separator: ", "))")).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }379            if !view.storedUnknownFields.isEmpty {380                Banner(.warning, "Le serveur a enregistré des limites que cette version de l’app ne connaît pas (\(view.storedUnknownFields.joined(separator: ", "))). L’édition est désactivée ici : enregistrer un nouvel ensemble les supprimerait.")381            } else if editing {382                Divider()383                Text("Champ vide = pas de limite enregistrée. Resserrer est immédiat ; tout assouplissement (valeur plus large ou limite retirée) vous sera montré puis demandera votre passkey. Les limites par actif, par plateforme et les listes ne sont pas modifiées ici et sont conservées.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)384                LazyVGrid(columns: [GridItem(.adaptive(minimum: 300), spacing: 12)], alignment: .leading, spacing: 8) {385                    ForEach(Self.decimals, id: \.0) { f in field(f.0, f.1) }386                    ForEach(Self.integers, id: \.0) { f in field(f.0, f.1) }387                }388                HStack {389                    if edited == nil { Text("Une valeur n’est pas un nombre valide.").font(.callout).foregroundStyle(Theme.negative) }390                    Spacer()391                    Button("Abandonner") { editing = false }392                    Button("Enregistrer les limites…") { if let l = edited { Task { await flow.saveLimits(mode: view.mode, limits: l); if flow.error == nil { editing = false } } } }393                        .buttonStyle(.borderedProminent).disabled(edited == nil || edited == view.stored || !model.canOperate || flow.busy)394                }395            } else {396                HStack { Spacer(); Button("Modifier les limites enregistrées…") { load(); editing = true }.disabled(!model.canOperate) }397            }398        }399    }400401    private func load() {402        var d: [String: String] = [:]403        for (k, _, path) in Self.decimals { d[k] = view.stored[keyPath: path] ?? "" }404        for (k, _, path) in Self.integers { d[k] = view.stored[keyPath: path].map(String.init) ?? "" }405        draft = d406    }407    private func field(_ key: String, _ label: String) -> some View {408        HStack { Text(label).font(.callout).frame(maxWidth: .infinity, alignment: .leading); TextField("aucune", text: Binding(get: { draft[key] ?? "" }, set: { draft[key] = $0 })).textFieldStyle(.roundedBorder).frame(width: 110) }409    }410    private func set(_ title: String, _ l: EngineRiskLimits) -> some View {411        VStack(alignment: .leading, spacing: 3) {412            Text(title).font(.callout.weight(.medium))413            let rows = Self.lines(l)414            if rows.isEmpty { Text("aucune limite").font(.callout).foregroundStyle(.secondary) }415            ForEach(rows, id: \.0) { r in416                HStack(alignment: .firstTextBaseline) { Text(r.0).font(.caption).foregroundStyle(.secondary); Spacer(minLength: 6); Text(r.1).font(.system(.caption, design: .monospaced)).textSelection(.enabled).lineLimit(3).multilineTextAlignment(.trailing) }417            }418        }.frame(maxWidth: .infinity, alignment: .topLeading)419    }420}421422// MARK: decisions423424private struct FutDecisionsCard: View {425    let decisions: [RiskDecision]426    var body: some View {427        Card("Journal du moteur de risque") {428            if decisions.isEmpty { Text("Aucune décision enregistrée.").foregroundStyle(.secondary) } else {429                Table(decisions) {430                    TableColumn("Date") { d in Text(Fmt.dateSeconds(d.date)).font(.callout) }.width(min: 130, ideal: 150)431                    TableColumn("Décision") { d in Text(d.decision + (d.preview ? " (aperçu)" : "")).fontWeight(.medium).foregroundStyle(d.denied ? Theme.negative : Theme.positive) }.width(min: 90, ideal: 110)432                    TableColumn("Objet") { d in Text("\(d.kind) · \(d.mode) · \(d.venue)" + (d.instrument.map { " · \($0)" } ?? "") + (d.reducing ? " · réducteur" : "")).font(.callout) }.width(min: 200, ideal: 280)433                    TableColumn("Auteur") { d in Text(d.principal.label).font(.caption).foregroundStyle(.secondary) }.width(min: 90, ideal: 130)434                    TableColumn("Contrôles en échec") { d in435                        let t = d.failing.map { f in "\(f.id) : \(f.detail)" + (f.observed.map { " — observé \($0)" } ?? "") + (f.limit.map { ", limite \($0)" } ?? "") }.joined(separator: " ; ")436                        Text(t.isEmpty ? "—" : t).font(.caption).lineLimit(2).help(t)437                    }.width(min: 200, ideal: 360)438                }.frame(height: CGFloat(min(decisions.count, 12)) * 30 + 36)439                Text("Chaque évaluation est consignée, aperçus compris ; un aperçu ne place rien.").font(.caption).foregroundStyle(.secondary)440            }441        }442    }443}444445// MARK: review sheet446447private struct FutRiskSheet: View {448    let model: AppModel449    @Bindable var flow: FutRiskFlow450    let sheet: FutRiskFlow.Sheet451452    var body: some View {453        VStack(alignment: .leading, spacing: 0) {454            FutSheetHeader(title: title)455            Divider()456            ScrollView { VStack(alignment: .leading, spacing: 14) { content }.padding(20) }457            Divider()458            VStack(alignment: .leading, spacing: 8) {459                if let e = flow.sheetError { Banner(.danger, e) }460                HStack {461                    Button("Fermer sans approuver") { flow.dismiss() }.disabled(flow.approving)462                    Spacer()463                    if flow.approving { ProgressView().controlSize(.small) }464                    Button { Task { await flow.approve() } } label: { Label("Approuver avec la passkey", systemImage: "touchid") }465                        .buttonStyle(.borderedProminent).controlSize(.large).disabled(flow.approving || !model.canOperate)466                }467            }.padding(16)468        }469        .frame(width: 700, height: 680).interactiveDismissDisabled()470    }471472    private var title: String {473        switch sheet {474        case .release(let a): a.kind == .killSwitch ? "Lever le coupe-circuit" : "Lever le mode lecture seule"475        case .limits(let a): "Assouplir les limites \(a.mode == .paper ? "papier" : "réelles")"476        case .auto: "Désactiver un arrêt automatique"477        }478    }479480    @ViewBuilder private var content: some View {481        switch sheet {482        case .release(let a):483            let i = a.intent484            Banner(.warning, a.kind == .killSwitch ? "Lever le coupe-circuit permet de nouveau à tous les ordres d’ajouter du risque, dans tous les modes." : "Lever le mode lecture seule permet de nouveau les ordres.")485            ReviewLines(lines: [486                .init(label: "Type d’opération", value: "Levée d’un commutateur global", style: .strong),487                .init(label: "Commutateur", value: i.kind.rawValue, style: .strong),488                .init(label: "Engagé le", value: FutNum.ms(i.engagedAt).map { Fmt.dateSeconds($0) } ?? "—"),489                .init(label: "Engagé par", value: i.engagedBy ?? "—"),490                .init(label: "Raison de l’engagement", value: i.reason.map { $0.isEmpty ? "(vide)" : $0 } ?? "—"),491                .init(label: "Nonce", value: i.nonce),492            ])493            BindingProof(digest: a.approval.digest, expiry: i.expiry)494        case .limits(let a):495            Banner(.warning, "Ces champs deviennent PLUS LARGES : \(a.loosened.joined(separator: ", ")).")496            ReviewLines(lines: [.init(label: "Type d’opération", value: "Nouvel ensemble de limites — mode \(a.mode.rawValue)", style: .strong)]497                        + FutLimitsCard.lines(a.limits).map { ReviewLine(label: $0.0, value: $0.1, style: a.loosened.contains($0.0) ? .warning : .normal) }498                        + [.init(label: "Nonce", value: a.intent.nonce)])499            Text("L’ensemble ci-dessus REMPLACE celui qui est enregistré : une limite qui n’y figure pas n’existe plus.").font(.callout).foregroundStyle(.secondary)500            BindingProof(digest: a.approval.digest, expiry: a.intent.expiry)501        case .auto(let a):502            Banner(.warning, "Arrêts désactivés par ce changement : \(a.loosened.joined(separator: ", ")).")503            ReviewLines(lines: [504                .init(label: "Type d’opération", value: "Réglage des arrêts automatiques", style: .strong),505                .init(label: "Perte totale", value: a.auto.totalLoss ? "actif" : "DÉSACTIVÉ", style: a.auto.totalLoss ? .normal : .warning),506                .init(label: "Drawdown", value: a.auto.drawdown ? "actif" : "DÉSACTIVÉ", style: a.auto.drawdown ? .normal : .warning),507                .init(label: "Perte quotidienne", value: a.auto.dailyLoss ? "actif" : "DÉSACTIVÉ", style: a.auto.dailyLoss ? .normal : .warning),508                .init(label: "Nonce", value: a.intent.nonce),509            ])510            BindingProof(digest: a.approval.digest, expiry: a.intent.expiry)511        }512    }513}514
Files main
Menu

Theme