SPB Git

Repository Public

QuantViews.swift 9.4 KB 177 lines swift

1//2//  VQuant iOS3//  File: VQuant/Features/Quant/QuantViews.swift4//  Description: Quantitative computations workspace (`/api/quant/*`): the server's engines, a parameter form built from5//               the server's own description, submitted jobs, and results with their parameters and code.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import SwiftUI1213struct QuantFormView: View {14    /// `toolId`, or `toolId|SYMBOL` to prefill the symbol.15    let toolId: String16    @Environment(AppModel.self) private var model17    @Environment(\.horizontalSizeClass) private var sizeClass18    @State private var values: [String: String] = [:]19    @State private var flags: [String: Bool] = [:]20    @State private var submitting = false21    @State private var error: String?22    @State private var prepared = false2324    private var id: String { String(toolId.split(separator: "|").first ?? "") }25    private var presetSymbol: String? { toolId.split(separator: "|").dropFirst().first.map(String.init) }26    private var tool: QuantTool? { model.quant.tool(id) }2728    var body: some View {29        Form {30            if let tool {31                Section { Text(tool.summary).font(.footnote).foregroundStyle(Theme.textSecondary) }32                Section("Paramètres") { ForEach(tool.params) { field($0) } }33                if let error { Section { Label(error, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down).accessibilityIdentifier("quant-error") } }34                Section {35                    Button {36                        Task { await submit(tool) }37                    } label: {38                        HStack { if submitting { ProgressView().controlSize(.small) }; Text("Lancer le calcul sur le serveur") }39                    }40                    .disabled(submitting).requiresNetwork(model.network.isOnline)41                    .accessibilityIdentifier("quant-submit")42                } footer: {43                    Text("Jusqu’à \(model.quant.tools.value?.maxRunning ?? 3) calculs simultanés. Un calcul lancé ne peut pas être annulé ; il n’engage aucune opération financière.")44                }45            } else if model.quant.tools.isUnavailable {46                StateView(kind: .failed, title: "Moteur indisponible", message: model.quant.tools.error?.message) { Task { await model.quant.refreshTools() } }47            } else { ProgressView() }48        }49        .navigationTitle(tool?.title ?? "Calcul").navigationBarTitleDisplayMode(.inline)50        .task {51            if model.quant.tools.value == nil { await model.quant.refreshTools() }52            prepare()53        }54    }5556    private func prepare() {57        guard !prepared, let tool else { return }58        prepared = true59        for p in tool.params {60            switch p.type {61            case "bool": flags[p.name] = p.default?.boolValue ?? false62            case "numbers": values[p.name] = (p.default?.arrayValue ?? []).compactMap { $0.doubleValue.map { Self.plain($0) } }.joined(separator: ", ")63            default:64                if let d = p.default { values[p.name] = d.stringValue ?? d.doubleValue.map { Self.plain($0) } ?? "" }65            }66        }67        if let s = presetSymbol {68            if tool.params.contains(where: { $0.name == "symbol" }) { values["symbol"] = s }69            else if tool.params.contains(where: { $0.name == "symbols" }) { values["symbols"] = s.replacingOccurrences(of: ",", with: ", ") }70        }71    }7273    private static func plain(_ v: Double) -> String { v == v.rounded() && abs(v) < 1e15 ? String(Int64(v)) : String(v) }7475    @ViewBuilder private func field(_ p: QuantParam) -> some View {76        let text = Binding(get: { values[p.name] ?? "" }, set: { values[p.name] = $0 })77        switch p.type {78        case "bool":79            Toggle(p.label, isOn: Binding(get: { flags[p.name] ?? false }, set: { flags[p.name] = $0 }))80        case "choice":81            Picker(p.label, selection: text) { ForEach(p.choices ?? [], id: \.self) { Text($0).tag($0) } }82        case "symbol", "symbols":83            LabeledContent(p.label + (p.required == true ? " *" : "")) {84                TextField(p.type == "symbols" ? "AAPL, MSFT, NVDA" : "AAPL", text: text)85                    .textInputAutocapitalization(.characters).autocorrectionDisabled().multilineTextAlignment(.trailing)86                    .accessibilityIdentifier("param-\(p.name)")87            }88        default:89            VStack(alignment: .leading, spacing: 2) {90                LabeledContent(p.label + (p.required == true ? " *" : "")) {91                    TextField(p.default == nil ? "—" : "", text: text)92                        .keyboardType(p.type == "numbers" ? .numbersAndPunctuation : (p.min ?? 0) < 0 ? .numbersAndPunctuation : .decimalPad)93                        .multilineTextAlignment(.trailing).monospacedDigit()94                        .accessibilityIdentifier("param-\(p.name)")95                }96                if let lo = p.min, let hi = p.max { Text("De \(Self.plain(lo)) à \(Self.plain(hi))").font(.caption2).foregroundStyle(Theme.textSecondary) }97            }98        }99    }100101    /// Typed parameters from the form. Empty optional fields are omitted so the server applies its own default.102    static func parameters(tool: QuantTool, values: [String: String], flags: [String: Bool]) -> [String: JSONValue] {103        var out: [String: JSONValue] = [:]104        func number(_ s: String) -> Double? { Double(s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")) }105        for p in tool.params {106            let raw = (values[p.name] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)107            switch p.type {108            case "bool": out[p.name] = .bool(flags[p.name] ?? false)109            case "symbol": if !raw.isEmpty { out[p.name] = .string(raw.uppercased()) }110            case "symbols":111                let list = raw.uppercased().split(whereSeparator: { ", ;\n".contains($0) }).map { JSONValue.string(String($0)) }112                if !list.isEmpty { out[p.name] = .array(list) }113            case "numbers":114                let list = Self.numberList(raw).map(JSONValue.number)115                if !list.isEmpty { out[p.name] = .array(list) }116            case "int", "number":117                if !raw.isEmpty { out[p.name] = number(raw).map(JSONValue.number) ?? .string(raw) }   // an unreadable number is sent as typed: the server names the field in its refusal118            default: if !raw.isEmpty { out[p.name] = .string(raw) }119            }120        }121        return out122    }123124    /// "0.9, 0.95" · "0,9 ; 0,95" · "0.9,0.95,0.99": values are separated by spaces or semicolons; a comma is a decimal125    /// mark only when it is the single comma of a value that has no point.126    static func numberList(_ raw: String) -> [Double] {127        raw.split(whereSeparator: { $0 == ";" || $0.isWhitespace }).flatMap { token -> [Double] in128            let t = token.trimmingCharacters(in: CharacterSet(charactersIn: ","))129            let commas = t.filter { $0 == "," }.count130            if commas == 1 && !t.contains(".") { return Double(t.replacingOccurrences(of: ",", with: ".")).map { [$0] } ?? [] }131            return t.split(separator: ",").compactMap { Double($0) }132        }133    }134135    private func submit(_ tool: QuantTool) async {136        submitting = true; error = nil137        defer { submitting = false }138        do {139            let job = try await model.quant.submit(tool: tool.id, params: Self.parameters(tool: tool, values: values, flags: flags))140            Haptics.success()141            Task { _ = await model.notifications.requestAuthorization() }142            model.router.open(.quantJob(job.id), compact: sizeClass == .compact)143        } catch let e { error = APIError.from(e).message; Haptics.warning() }144    }145}146147struct QuantResultView: View {148    let result: JSONValue149    var body: some View {150        ForEach(QuantResult.sections(result)) { section in151            Card(Fmt.label(section.title), systemImage: icon(section.body)) {152                switch section.body {153                case .values(let rows):154                    VStack(spacing: 6) { ForEach(rows) { KeyValueRow(key: Fmt.label($0.key), value: QuantResult.format($0.value)) } }.textSelection(.enabled)155                case .series(let points):156                    SeriesChart(points: points, title: Fmt.label(section.title)).frame(height: 200)157                case .table(let table):158                    ScrollView(.horizontal) {159                        Grid(alignment: .trailing, horizontalSpacing: 14, verticalSpacing: 6) {160                            GridRow { ForEach(Array(table.columns.enumerated()), id: \.offset) { _, c in Text(Fmt.label(c)).font(.caption2.weight(.semibold)).frame(maxWidth: 110) } }161                            Divider()162                            ForEach(Array(table.rows.enumerated()), id: \.offset) { _, row in163                                GridRow { ForEach(Array(row.enumerated()), id: \.offset) { i, cell in Text(cell).font(i == 0 ? .caption.weight(.semibold) : .caption.monospacedDigit()) } }164                            }165                        }166                    }167                case .notes(let notes):168                    VStack(alignment: .leading, spacing: 4) { ForEach(notes, id: \.self) { Text("• \($0)").font(.footnote) } }169                }170            }171        }172    }173    private func icon(_ b: QuantResult.Body) -> String {174        switch b { case .values: "list.bullet"; case .series: "chart.xyaxis.line"; case .table: "tablecells"; case .notes: "text.alignleft" }175    }176}177
Files main
Menu

Theme