Repository Public
1// SP Wallet iOS2// File: Features/Security/MandateCreateFlow.swift3// Description: Creation of a trading mandate (paper or live) for an API key or an agent. Every limit — budget, per-order cap,4// position cap, leverage, loss limits, markets, order types, frequency, slippage, fees, expiry — starts EMPTY and is5// typed by the owner; the button stays disabled while anything is missing. Creating gives no authority: the mandate6// is then reviewed in full and approved (paper: session; live: two passkey prompts).7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213@MainActor @Observable14final class MandateCreateModel {15 struct Choice: Identifiable, Hashable { let id: String; let name: String; var venue = ""; var strategy: String?; var pinned: [String] = [] }16 var draft = TradingMandateDraft()17 var keys: [Choice] = []18 var agents: [Choice] = []19 var paperAccounts: [Choice] = []20 var liveAccounts: [Choice] = []21 var venueInstruments: [String: [String]] = [:]22 var sourceErrors: [String] = []23 var busy = false24 var error: Error?25 var created: (record: TradingMandateRecord, request: MandateCreateRequest)?26 var instrumentText = ""2728 var principals: [Choice] { draft.principalKind == "api_key" ? keys : draft.principalKind == "agent" ? agents : [] }29 var accounts: [Choice] { draft.mode == .paper ? paperAccounts : draft.mode == .live ? liveAccounts : [] }30 var account: Choice? { accounts.first { $0.id == draft.accountId } }31 /** The markets a mandate may name: live = the set the venue authorization pins; paper = the venue's own list. */32 var selectable: [String] { guard let a = account else { return [] }; return draft.mode == .live ? a.pinned : venueInstruments[a.venue] ?? [] }3334 func loadSources(_ app: AppModel) async {35 let c = app.env.client36 sourceErrors = []37 do { keys = try await DeveloperAPI(c).keys().keys.filter(\.isActive).map { Choice(id: $0.id, name: "\($0.name) · \($0.id)") } } catch { sourceErrors.append(String(localized: "clés d’API")) }38 do { agents = try await AgentsAPI(c).list().map { Choice(id: $0.id, name: $0.name + ($0.kind == .perp ? " · perp" : ""), strategy: $0.mandate?.strategySha256) } } catch { sourceErrors.append(String(localized: "agents")) }39 do { paperAccounts = try await DerivativesAPI(c).paperAccounts().map { Choice(id: $0.id.rawValue, name: "\($0.label) · \($0.venue)", venue: $0.venue) } } catch { sourceErrors.append(String(localized: "comptes papier")) }40 do {41 liveAccounts = try await DerivativesLiveAPI(c).accounts().filter { $0.authorization != nil }42 .map { Choice(id: $0.id.rawValue, name: "\($0.label.isEmpty ? $0.venue : $0.label) · \($0.venue) \($0.network)", venue: $0.venue, pinned: $0.authorization?.policy.allowedInstruments ?? []) }43 } catch { sourceErrors.append(String(localized: "comptes réels")) }44 }4546 func loadInstruments(_ app: AppModel) async {47 guard draft.mode == .paper, let a = account, venueInstruments[a.venue] == nil else { return }48 if let r = try? await DerivativesAPI(app.env.client).instruments(venue: a.venue) { venueInstruments[a.venue] = r.instruments.map(\.id) }49 }5051 func addInstruments() {52 let allowed = selectable53 for i in RiskInput.list(instrumentText) where !draft.instruments.contains(i) && (allowed.isEmpty || allowed.contains(i)) { draft.instruments.append(i) }54 instrumentText = ""55 }5657 /** POST /mandates is not idempotent: after a lost answer the list is read before anything is created again. */58 func create(_ app: AppModel) async {59 guard !busy, let r = draft.request(locale: Locale.current.language.languageCode?.identifier == "en" ? "en" : "fr") else { return }60 busy = true; error = nil; defer { busy = false }61 let api = MandatesAPI(app.env.client)62 do { created = (try await api.create(r), r) }63 catch let e as APIError where e.isOffline {64 if let found = try? await api.list().first(where: { $0.state == "created" && $0.label == r.label && $0.principal == r.principal && ($0.mandate.map { (try? MandatesAPI.check(mandate: $0, against: r)) != nil } ?? false) }) {65 created = (found, r)66 } else { error = e }67 } catch { self.error = error }68 }69}7071struct MandateCreateFlow: View {72 @Environment(AppModel.self) private var model73 @Environment(\.dismiss) private var dismiss74 @State private var create = MandateCreateModel()75 @State private var approval = MandateApprovalModel()7677 var body: some View {78 NavigationStack {79 ScrollView {80 VStack(alignment: .leading, spacing: Theme.Space.section) {81 if let c = create.created {82 Notice(tone: .info, title: String(localized: "Mandat créé, sans effet tant qu’il n’est pas approuvé"), message: String(localized: "Le serveur a enregistré exactement les limites saisies (vérifié par l’app)."))83 .accessibilityIdentifier("mandate.created")84 MandateApprovalContent(flow: approval, mandateId: c.record.id, expecting: .request(c.request)) { dismiss() }85 } else { form }86 }87 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)88 .frame(maxWidth: 680).frame(maxWidth: .infinity)89 }90 .spPage()91 .navigationTitle(create.created == nil ? String(localized: "Nouveau mandat") : String(localized: "Vérifier et approuver")).navigationBarTitleDisplayMode(.inline)92 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(create.created == nil ? String(localized: "Annuler") : String(localized: "Fermer")) { dismiss() }.disabled(create.busy || approval.busy).accessibilityIdentifier("mandate.new.close") } }93 .task { await create.loadSources(model) }94 }95 .interactiveDismissDisabled(create.created != nil || create.busy)96 }9798 @ViewBuilder private var form: some View {99 @Bindable var create = create100 Text(String(localized: "Aucune valeur n’est proposée : chaque limite est la tienne. Créer un mandat ne donne aucune autorité ; il faudra ensuite le revoir en entier et l’approuver."))101 .font(.spFootnote).foregroundStyle(Theme.mute)102 if !create.sourceErrors.isEmpty { Notice(tone: .warn, title: String(localized: "Listes illisibles pour le moment"), message: create.sourceErrors.joined(separator: " · ")) }103104 VStack(alignment: .leading, spacing: 10) {105 Text(String(localized: "Bénéficiaire")).font(.spHeadline)106 Picker(String(localized: "Type de bénéficiaire"), selection: Binding(get: { create.draft.principalKind ?? "" }, set: { create.draft.principalKind = $0.isEmpty ? nil : $0; create.draft.principalId = ""; create.draft.strategySha256 = "" })) {107 Text(String(localized: "Choisir")).tag(""); Text(String(localized: "Clé d’API")).tag("api_key"); Text(String(localized: "Agent")).tag("agent")108 }.pickerStyle(.segmented).accessibilityIdentifier("mandate.new.principalKind")109 if create.draft.principalKind != nil {110 if create.principals.isEmpty { Text(create.draft.principalKind == "api_key" ? String(localized: "Aucune clé d’API active. Crée-en une d’abord (Clés d’API).") : String(localized: "Aucun agent.")).font(.spFootnote).foregroundStyle(Theme.warn) }111 Picker(String(localized: "Bénéficiaire"), selection: Binding(get: { create.draft.principalId }, set: { id in112 create.draft.principalId = id113 if create.draft.principalKind == "agent" { create.draft.strategySha256 = create.agents.first { $0.id == id }?.strategy ?? "" }114 })) {115 Text("—").tag(""); ForEach(create.principals) { Text($0.name).tag($0.id) }116 }.pickerStyle(.menu).accessibilityIdentifier("mandate.new.principal")117 }118 if create.draft.principalKind == "agent" {119 field(String(localized: "Empreinte SHA-256 de la stratégie (64 caractères hexadécimaux)"), $create.draft.strategySha256, .asciiCapable, "mandate.new.sha", mono: true)120 }121 }.spCard()122123 VStack(alignment: .leading, spacing: 10) {124 Text(String(localized: "Mode et compte")).font(.spHeadline)125 Picker(String(localized: "Mode"), selection: Binding(get: { create.draft.mode?.rawValue ?? "" }, set: { create.draft.mode = RiskMode(rawValue: $0); create.draft.accountId = ""; create.draft.instruments = [] })) {126 Text(String(localized: "Choisir")).tag(""); Text(String(localized: "PAPIER")).tag("paper"); Text(String(localized: "RÉEL")).tag("live")127 }.pickerStyle(.segmented).accessibilityIdentifier("mandate.new.mode")128 if create.draft.mode == .live { Notice(tone: .warn, title: String(localized: "Mandat RÉEL"), message: String(localized: "Il portera sur des fonds réels une fois approuvé par deux demandes de clé d’accès. Durée maximale : 30 jours. Le compte doit déjà avoir une autorisation de plateforme.")) }129 if create.draft.mode == .paper { Notice(tone: .info, title: String(localized: "Mandat PAPIER (simulation)"), message: String(localized: "Aucun fonds réel. Durée maximale : 90 jours.")) }130 if create.draft.mode != nil {131 if create.accounts.isEmpty { Text(create.draft.mode == .live ? String(localized: "Aucun compte réel avec autorisation. Les comptes se préparent dans Contrats à terme.") : String(localized: "Aucun compte papier. Les comptes papier se créent dans Contrats à terme.")).font(.spFootnote).foregroundStyle(Theme.warn).accessibilityIdentifier("mandate.new.noAccount") }132 Picker(String(localized: "Compte"), selection: Binding(get: { create.draft.accountId }, set: { create.draft.accountId = $0; create.draft.instruments = []; Task { await create.loadInstruments(model) } })) {133 Text("—").tag(""); ForEach(create.accounts) { Text($0.name).tag($0.id) }134 }.pickerStyle(.menu).accessibilityIdentifier("mandate.new.account")135 }136 }.spCard()137138 if create.account != nil {139 VStack(alignment: .leading, spacing: 10) {140 Text(String(localized: "Marchés autorisés")).font(.spHeadline)141 Text(create.draft.mode == .live ? String(localized: "Seuls les marchés épinglés par l’autorisation de la plateforme peuvent être nommés.") : String(localized: "Identifiants « plateforme:symbole » de la plateforme du compte."))142 .font(.spFootnote).foregroundStyle(Theme.mute)143 let options = create.selectable144 if !options.isEmpty, options.count <= 12 {145 ForEach(options, id: \.self) { i in check(i, create.draft.instruments.contains(i), mono: true, id: "mandate.new.inst.\(i)") { toggle(&create.draft.instruments, i) } }146 } else {147 HStack {148 field(String(localized: "ex. \(create.account?.venue ?? "plateforme"):BTC"), $create.instrumentText, .asciiCapable, "mandate.new.instText", mono: true)149 Button(String(localized: "Ajouter")) { create.addInstruments() }.buttonStyle(.bordered).accessibilityIdentifier("mandate.new.instAdd")150 }151 if !options.isEmpty { Text(String(localized: "\(options.count) marchés connus sur cette plateforme ; un identifiant inconnu est ignoré.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }152 ForEach(create.draft.instruments, id: \.self) { i in153 HStack { Text(i).font(.spMono); Spacer(); Button { create.draft.instruments.removeAll { $0 == i } } label: { Image(systemName: "minus.circle.fill").foregroundStyle(Theme.danger) }.frame(minWidth: 44, minHeight: 36).accessibilityLabel(String(localized: "Retirer \(i)")) }154 }155 }156 Text(String(localized: "Types de marché")).font(.spCallout.weight(.semibold)).padding(.top, 4)157 ForEach(TradingMandateDraft.marketKinds, id: \.self) { k in check(k == "perp" ? String(localized: "contrats perpétuels (perp)") : String(localized: "au comptant (spot)"), create.draft.marketKinds.contains(k), id: "mandate.new.kind.\(k)") { toggle(&create.draft.marketKinds, k) } }158 Text(String(localized: "Types d’ordre")).font(.spCallout.weight(.semibold)).padding(.top, 4)159 ForEach(TradingMandateDraft.orderTypes, id: \.self) { t in check(MandateWords.orderType(t), create.draft.orderTypes.contains(t), id: "mandate.new.type.\(t)") { toggle(&create.draft.orderTypes, t) } }160 }.spCard()161 }162163 VStack(alignment: .leading, spacing: 12) {164 Text(String(localized: "Limites (USD)")).font(.spHeadline)165 labelled(String(localized: "Budget : capital que le bénéficiaire peut mettre à risque"), $create.draft.budgetCap, .decimalPad, "mandate.new.capital")166 labelled(String(localized: "Plafond par ordre"), $create.draft.perOrderCap, .decimalPad, "mandate.new.order")167 labelled(String(localized: "Plafond de position, par marché"), $create.draft.positionCap, .decimalPad, "mandate.new.position")168 labelled(String(localized: "Levier maximal (×)"), $create.draft.maxLeverage, .decimalPad, "mandate.new.leverage")169 labelled(String(localized: "Perte maximale par jour — appliquée par l’API"), $create.draft.dailyLossLimit, .decimalPad, "mandate.new.dailyloss")170 labelled(String(localized: "Plancher de fonds propres : sous ce niveau, plus de nouveau risque (0 accepté)"), $create.draft.floorEquity, .decimalPad, "mandate.new.floor")171 labelled(String(localized: "Frais maximal d’un ordre (0 accepté)"), $create.draft.maxFee, .decimalPad, "mandate.new.fee")172 }.spCard()173174 VStack(alignment: .leading, spacing: 12) {175 Text(String(localized: "Durée, cadence, glissement")).font(.spHeadline)176 labelled(create.draft.mode.map { String(localized: "Durée en jours (1 à \(TradingMandateDraft.maxDays($0)))") } ?? String(localized: "Durée en jours"), $create.draft.days, .numberPad, "mandate.new.days")177 labelled(String(localized: "Ordres par minute (au moins 1)"), $create.draft.perMinute, .numberPad, "mandate.new.permin")178 labelled(String(localized: "Ordres par heure (au moins 1)"), $create.draft.perHour, .numberPad, "mandate.new.perhour")179 labelled(String(localized: "Ordres par 24 h (au moins 1)"), $create.draft.perDay, .numberPad, "mandate.new.perday")180 labelled(String(localized: "Glissement maximal (pb, au moins 1)"), $create.draft.slippageBps, .numberPad, "mandate.new.slippage")181 }.spCard()182183 VStack(alignment: .leading, spacing: 12) {184 Text(String(localized: "Conditions d’arrêt (facultatives)")).font(.spHeadline)185 Text(String(localized: "Quand l’une est atteinte, le mandat ne prend plus de nouveau risque. Vide = pas de condition.")).font(.spFootnote).foregroundStyle(Theme.mute)186 ForEach(TradingMandateDraft.stops, id: \.kind) { s in187 labelled(MandateWords.stopTitle(s.kind), Binding(get: { create.draft.stops[s.kind] ?? "" }, set: { create.draft.stops[s.kind] = $0 }), s.decimal ? .decimalPad : .numberPad, "mandate.new.stop.\(s.kind)")188 }189 }.spCard()190191 VStack(alignment: .leading, spacing: 10) {192 Text(String(localized: "Nom du mandat")).font(.spHeadline)193 field(String(localized: "1 à 60 caractères"), $create.draft.label, .default, "mandate.new.label")194 }.spCard()195196 let problems = create.draft.problems()197 if !problems.isEmpty {198 Text(String(localized: "Reste à saisir : \(problems.map(MandateWords.problem).joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("mandate.new.problems")199 }200 if let e = create.error { ErrorNotice(error: e).accessibilityIdentifier("mandate.new.error") }201 Button { Task { await create.create(model) } } label: { HStack { if create.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Créer et passer à la revue")) } }202 .buttonStyle(.spPrimary).disabled(!problems.isEmpty || create.busy || !model.canOperate).accessibilityIdentifier("mandate.new.create")203 }204205 private func toggle<C: RangeReplaceableCollection>(_ c: inout C, _ v: String) where C.Element == String { if let i = c.firstIndex(of: v) { c.remove(at: i) } else { c.append(v) } }206 private func toggle(_ s: inout Set<String>, _ v: String) { if s.contains(v) { s.remove(v) } else { s.insert(v) } }207208 private func check(_ text: String, _ on: Bool, mono: Bool = false, id: String, flip: @escaping () -> Void) -> some View {209 Button(action: flip) {210 HStack(spacing: 10) {211 Image(systemName: on ? "checkmark.square.fill" : "square").font(.system(size: 20)).foregroundStyle(on ? Theme.blue : Theme.mute)212 Text(text).font(mono ? .spMono : .spBody).foregroundStyle(Theme.ink)213 Spacer()214 }.frame(minHeight: 44).contentShape(Rectangle())215 }216 .buttonStyle(.plain).accessibilityIdentifier(id).accessibilityValue(on ? String(localized: "coché") : String(localized: "non coché"))217 }218219 private func labelled(_ label: String, _ text: Binding<String>, _ kb: UIKeyboardType, _ id: String) -> some View {220 VStack(alignment: .leading, spacing: 5) {221 Text(label).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)222 field(String(localized: "à saisir"), text, kb, id)223 }224 }225 private func field(_ placeholder: String, _ text: Binding<String>, _ kb: UIKeyboardType, _ id: String, mono: Bool = false) -> some View {226 TextField(placeholder, text: text)227 .keyboardType(kb).textInputAutocapitalization(.never).autocorrectionDisabled().font(mono ? .spMono : .spBody).monospacedDigit()228 .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))229 .accessibilityIdentifier(id)230 }231}232